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!
I'm a big fan of ternary op too.
ReplyDeleteI 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. :)
Impressing :) Wouldn't thought of that. Not that easy to read but it works.
ReplyDelete