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!

2 comments:

  1. I'm a big fan of ternary op too.

    I just fooled around a bit and noticed that following construct does the trick as well:
    (b, a)[a > b]

    I won't probably use that anywhere but I thought it might be a fun little oneliner to share. :)

    ReplyDelete
  2. Impressing :) Wouldn't thought of that. Not that easy to read but it works.

    ReplyDelete