Sunday, March 1, 2009

Conditional expression in Python

It has bothered me for a long time that Python does not provide a conditional expression operator similar to the ?: operator used in C. But by some fortune, I ran across this Python snippet:

("False", "True")[var == True]

which does exactly the same as what you would write in C

var ? "True" : "False"

What a relief!