Is there a ternary conditional operator in Python?
Yes, it was added in version 2.5. The expression syntax is:
a if condition else b
condition is evaluated, then exactly one of either
b is evaluated and returned based on the Boolean value of
condition evaluates to
a is evaluated and returned but
b is ignored, or else when
b is evaluated and returned but
a is ignored.
This allows short-circuiting because when
condition is true only
a is evaluated and
b is not evaluated at all, but when
condition is false only
b is evaluated and
a is not evaluated at all.
>>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false'
Note that conditionals are an expression, not a statement. This means you can't use assignment statements or
pass or other statements within a conditional expression:
>>> pass if False else x = 3 File "<stdin>", line 1 pass if False else x = 3 ^ SyntaxError: invalid syntax
You can, however, use conditional expressions to assign a variable like so:
x = a if True else b
Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, but it doesn't do much else.
If you need to use statements, you have to use a normal
if statement instead of a conditional expression.
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
if' can be really useful, and make your script more concise, it really does complicate your code)
If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example,
x = 4 if b > 8 else 9 is read aloud as
x will be 4 if b is greater than 8 otherwise 9.
f(x) = |x| = x if x > 0 else -xsounds very natural to mathematicians. You may also understand it as do A in most case, except when C then you should do B instead... — Jan 25, 2016 at 15:07
z = 3 + x if x < y else y. If
y=1, you might expect that to yield 4, but it would actually yield 1.
z = 3 + (x if x > y else y)is the correct usage. — Mar 06, 2016 at 09:23
z = 3 + x if x < y else 3 + y), or group the conditional (
z = 3 + (x if x < y else y)or
z = (x if x < y else y) + 3) — Apr 15, 2016 at 00:36
External links referenced by this document: