python conditional operator must end with else in comprehensions? [duplicate]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
Solution 1:
Yes, it was added in version 2.5. The expression syntax is:
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 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, it but 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:
- The order of the arguments is different from those of the classic
condition ? a : b
ternary 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?
Solution 2:
You can index into a tuple:
(falseValue, trueValue)[test]
test
needs to return True or False.
It might be safer to always implement it as:
(falseValue, trueValue)[test == True]
or you can use the built-in bool()
to assure a Boolean value:
(falseValue, trueValue)[bool(<expression>)]
Solution 3:
For versions prior to 2.5, there's the trick:
[expression] and [on_true] or [on_false]
It can give wrong results when on_true
has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.
1. Is there an equivalent of C’s ”?:” ternary operator?
Solution 4:
<expression 1> if <condition> else <expression 2>
a = 1
b = 2
1 if a > b else -1
# Output is -1
1 if a > b else -1 if a < b else 0
# Output is -1