Python Conditional Expression
Conditional Expressions (also known as Ternary Operators) are used to write an if
statement in one line.
Conditional Expressions
if-else Conditional Expression
In Python, conditional expression syntax is as follows:
value_if_true if condition else value_if_false
where:
- The
condition
is evaluated first. - If
condition
isTrue
,value_if_true
is evaluated and its value is returned - If
condition
isFalse
,value_if_false
is evaluated and its value is returned
For example:
a = 1
result = 'even' if a % 2 == 0 else 'odd'
print(result) # odd
a = 2
result = 'even' if a % 2 == 0 else 'odd'
print(result) # even
The equivalent extended form is:
if a % 2 == 0:
result = 'even'
else:
result = 'odd'
An expression that does not return a value (i.e., an expression that returns None
) is also acceptable.
a = 1
print('even') if a % 2 == 0 else print('odd') # odd
You can also concatenate multiple conditional expressions with and
and or
.
a = -2
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result) # negative and even
if-elif-else
by conditional expressions
value_if_true if condition1 else value_if_true2 if condition2 else value_else
For example:
a = 2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result) # positive
Conditional Expressions with Tuple Notation
An alternative but very little-used form of Conditional Expressions involves tuples.
(if_test_is_false, if_test_is_true)[condition]
For example:
num = 10
result = ("Even", "Odd")[num % 2]
print("The number is ", result) # The number is Even
If the condition is true, the value at position 1 of the tuple is returned, otherwise the value at position 0 is returned.
It is easy to confuse where to put the true value and where to put the false value in the tuple. Also, both elements of the tuple are evaluated, whereas the ternary if-else operator does not, and this can lead to errors.
condition = True
print(2 if condition else 1/0) # 2
print((1/0, 2)[condition])
#ZeroDivisionError is raised
Common cases
Conditional Expressions in List Comprehensions
Using conditional expressions in list comprehension, you can apply operations to list elements based on the condition.
my_list = ['even' if i % 2 == 0 else 'odd' for i in range(10)]
print(my_list)
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
l = [i * 2 if i % 2 == 0 else i for i in range(10)]
print(l)
# [0, 1, 4, 3, 8, 5, 12, 7, 16, 9]