01 February 2011

Python ternary operator

Holy crap, a year and no update. In an attempt to get things going again, here's a simple post of something I keep looking up online.

Python has no ternary operator (?: in C++)

Instead, use an and-or construction:

In [1]: True and 'a' or 'b'
Out[1]: 'a'
In [2]: False and 'a' or 'b'
Out[2]: 'b'

Replace True and False with the condition:

In [3]: (1==1) and 'a' or 'b'
Out[3]: 'a'
In [4]: (1==0) and 'a' or 'b'
Out[4]: 'b'


One failure of this method is then 'a' or 'b' can evaluate as boolean values. Examples of this behavior:

In [1]: True and True or False
Out[1]: True

In [2]: True and False or True
Out[2]: True

In [3]: True and 1 or 0
Out[3]: 1

In [4]: True and 0 or 1
Out[4]: 1

In [5]: True and 'a' or ''
Out[5]: 'a'

In [6]: True and '' or 'a'
Out[6]: 'a'

So you see that if the first return value evaluates as false, the second value is returned. I'll post a solution or workaround later, when I find one.

1 comment:

Johndavies said...