Python ternary operator

Today’s Python discovery:

Python doesn’t have the C style ?: ternary operator (e.g.: cond ? valueIfTrue : valueIfFalse).

But as of Python 2.5 it has a ternary operator with its own syntax: value_when_true if condition else value_when_false

For example:

>>> 'a' if 1 == 1 else 'b'
'a'
>>> 'a' if 1 == 0 else 'b'
'b'

This is actually clearer and more Pythonic than that ?:

Unfortunately, for Python versions < 2.5, you don’t have this. I’ve seen people use: (condition and [value_when_true] or [value_when_false])[0]

IMHO, this is clever – in a bad way. Yuck. Personally, I think I’d rather just do:


def if_cond_val1_else_val2(cond, val1, val2): 
   if cond: return val1
   else: return val2

This adds 3 lines to your program (or 1 if you stick it in a module that you import from your programs) and won’t cause your colleagues to hate you.