Friday, March 19, 2010

Ternary operation

I'm a big fan of using ternary operations when possible but Python didn't introduced them until the 2.5 release, see Wikipedia page. Before the 2.5 release there existed options like using the and and or operator
x and y or z
or a lambda construction, but none if them are considered foolproof (see the wiki page for explanation). So how do you write the ternary operation in python?
a, b = 1, 2

# non ternary operation
if a > b:
    z = a
else:
    z = b

# rewritten to

z = a if a > b else b
Clean, readable and simple!