Simulating the Ternary Operator in Python
Credit: Jürgen Hermann, Alex Martelli, Oliver Steele, Lloyd Goldwasser, Chris Perkins, and Brent Burley
Problem
You want to express in Python the
equivalent of C’s so-called ternary operator
?: (as in,
condition?iftrue:iffalse).
Solution
There are many ways to skin a ternary operator. An explicit
if/else is most Pythonic, but
somewhat verbose:
for i in range(1, 3):
if i == 1:
plural = ''
else:
plural = 's'
print "The loop ran %d time%s" % (i, plural)Indexing is compact if there are no side effects in the
iftrue and
iffalse expressions:
for i in range(1, 3):
print "The loop ran %d time%s" % (i, ('', 's')[i != 1])For the specific case of plurals, there’s also a neat variant using slicing:
for i in range(1, 3):
print "The loop ran %d time%s" % (i, "s"[i==1:])Short-circuited logical expressions can deal correctly with side effects:
for i in range(1, 3):
print "The loop ran %d time%s" % (i, i != 1 and 's' or '')The output of each of these loops is:
The loop ran 1 time The loop ran 2 times
However, the short circuit (which is necessary when either or both of
iftrue and
iffalse have side effects) fails if turned
around:
for i in range(1, 3):
print "The loop ran %d time%s" % (i, i == 1 and '' or 's')Since '' evaluates as false, this snippet outputs:
The loop ran 1 times The loop ran 2 times
So generally, when iftrue and
iffalse are unknown at coding time (either
could have side effects or be false), we need:
for i in range(1, 3): print "The loop ran %d ...