More things I didn't know about Python

As you’ve probably noticed over the last few days, I like Python a lot.

Last night I found a new (to me) thing. It’s a new to Python 2.5, which might preclude it from being useful in older projects. In C and C++, one of the more useful constructs in expressions is the ternary operator:

minimumOfXandY = (x < y) ? x : y;

In Python prior to 2.5 you could use the fact that the logical and and or features test for truth, but return the actual objects involved — a little counterintuitively you would write:

minimumOfXandY = (x < y) and x or y

In Python 2.5 there’s a slightly more readable syntax:

minimumOfXandY = x if (x < y) else y

I don’t think it’s quite as nice as the C style way of doing things, as the values and the conditional are in a non-intuitive order for imperative languages. But arguably it’s a little better than the and/or idiom.

Filed under: Coding
Posted at 12:35:00 GMT on 7th November 2007.

About Matt Godbolt

Matt Godbolt is a C++ developer working in Chicago for Aquatic. Follow him on Mastodon.