Ternary Operator in Python

C-like languages such as C# have a ternary operator which uses the symbols: ? and :, while the actual syntax looks something like this:

string s = myBoolValue ? 'True' : 'False';

Python doesn’t feature a ternary operator as in the C-like languages, but the underlying behavior is supported. You can achieve this in one of two ways:

  • s = 'True' if myBoolValue else 'False'
  • s = myBoolValue and 'True' or 'False'

The if form in number 1 above was introduced in Python 2.5 to address feature requests for a ternary conditional form (see PEP 308).

The form in number 2 above is a clever way to achieve the same effect using short circuiting. The conditional form in number 1 is the preferred form as the technique in number 2 is error-prone.

Update: 2009-09-25

With the ternary example number 2 above there is a small caveat that didn't occur to me until today. Consider the following code:

(a,b) = ('abc','xyz')
print True and a or b
print False and a or b

The above code is fine and behaves as expected. But what if the value of a turned out to be equal to a Python False? That would give us a wrong result... Consider the following code:

>>> (a,b) = ('', 'xyz')
>>> print True and a or b
xyz
>>> print False and a or b
xyz

See the conundrum? The real trick is to make sure that the value of a is never false. One way to fix this is to turn a and b into lists and the whole expression into a tuple and then read out the first element returned, like so:

>>> (a,b) = ('', 'xyz')
>>> print (True and [a] or [b])[0]

>>> print (False and [a] or [b])[0]
xyz

The first print statement now returns an empty string as expected.

Comments

Comments powered by Disqus