patternpythonCritical
Does Python have a ternary conditional operator?
Viewed 0 times
havepythonoperatordoesconditionalternary
Problem
Is there a ternary conditional operator in Python?
Solution
Yes, it was added in version 2.5. The expression syntax is:
First
This allows short-circuiting because when
For example:
Note that conditionals are an expression, not a statement. This means you can't use statements such as
(In 3.8 and above, the
Similarly, because it is an expression, the
You can, however, use conditional expressions to assign a variable like so:
Or for example to return a value:
Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example,
Official documentation:
a if condition else b
First
condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then 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.For example:
>>> '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 statements such as
pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression:>>> pass if False else pass
File "", line 1
pass if False else pass
^
SyntaxError: invalid syntax
>>> # Python parses this as x = (1 if False else y) = 2
>>> # The (1 if False else x) part is actually valid, but
>>> # it can't be on the left-hand side of =.
>>> x = 1 if False else y = 2
File "", line 1
SyntaxError: cannot assign to conditional expression
>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax
(In 3.8 and above, the
:= "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)Similarly, because it is an expression, the
else part is mandatory:# Invalid syntax: we didn't specify what the value should be if the
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if TrueYou can, however, use conditional expressions to assign a variable like so:
x = a if True else b
Or for example to return a value:
# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else bThink of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal
if statement instead.Keep in mind that it's frowned upon by some Pythonistas for several reasons:
- The order of the arguments is different from those of the classic
condition ? a : bternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
- Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
- Stylistic reasons. (Although the 'inline
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.Official documentation:
- Conditional expressions
- Is there an equivalent of C’s ”?:” ternary operator?
Code Snippets
# Invalid syntax: we didn't specify what the value should be if the
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else bContext
Stack Overflow Q#394809, score: 9352
Revisions (0)
No revisions yet.