Python has a writing style called ternary operators (conditional operators) that can describe a process like an if statement in a single line.
The following is explained here, along with sample code.
- Basic writing of ternary operators
if ... elif ... else ...
Describe this in one line- Combining List Comprehensive Notation and Ternary Operators
- Combination of anonymous functions (lambda expressions) and ternary operators
See the following article for more information on the normal if statement.
Basic writing of ternary operators
In Python, the ternary operator can be written as follows
Expression evaluated when the conditional expression is true if conditional expression else Expression evaluated when the conditional expression is false
If you want to switch values according to conditions, simply write each value as it is.
Value to return if conditional expression is true if conditional expression else Value to return if conditional expression is false
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
If you want to switch processing according to conditions, describe each expression.
a = 1
result = a * 2 if a % 2 == 0 else a * 3
print(result)
# 3
a = 2
result = a * 2 if a % 2 == 0 else a * 3
print(result)
# 4
Expressions that do not return a value (expressions that return None) are also acceptable. Depending on the condition, one of the expressions is evaluated and the process is executed.
a = 1
print('even') if a % 2 == 0 else print('odd')
# odd
Equivalent to the following code written with a normal if statement.
a = 1
if a % 2 == 0:
print('even')
else:
print('odd')
# odd
Multiple conditional expressions can also be concatenated using logical operators (and, or, etc.).
a = -2
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# negative and even
a = -1
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# positive or odd
if ... elif ... else ...One-line description
if ... elif ... else ...
There is no special way to write this on a single line. However, it can be realized by using another ternary operator in the expression that is evaluated when the conditional expression of the ternary operator is false. Image of nesting ternary operators.
However, it may be best not to use it extensively because it reduces readability.
a = 2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# positive
a = 0
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# zero
a = -2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# negative
The following conditional expression can be interpreted in the following two ways, but is treated as the former (1).
A if condition 1 else B if condition 2 else C
1. A if condition 1 else ( B if condition 2 else C )
2. ( A if condition 1 else B ) if condition 2 else C
A concrete example is as follows. The first expression is regarded as if it were the second.
a = -2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# negative
result = 'negative' if a < 0 else ('positive' if a > 0 else 'zero')
print(result)
# negative
result = ('negative' if a < 0 else 'positive') if a > 0 else 'zero'
print(result)
# zero
Combining List Comprehensive Notation and Ternary Operators
A useful use of the ternary operator is when processing lists in list comprehension notation.
By combining the ternary operator and list comprehension notation, it is possible to replace elements of a list or perform some other processing depending on the conditions.
l = ['even' if i % 2 == 0 else i for i in range(10)]
print(l)
# ['even', 1, 'even', 3, 'even', 5, 'even', 7, 'even', 9]
l = [i * 10 if i % 2 == 0 else i for i in range(10)]
print(l)
# [0, 1, 20, 3, 40, 5, 60, 7, 80, 9]
For more information on list comprehension notation, see the following article.
Combination of anonymous functions (lambda expressions) and ternary operators
The ternary operator, which can be described concisely even in an anonymous function (lambda expression), is useful.
get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd'
print(get_odd_even(1))
# odd
print(get_odd_even(2))
# even
Note that, although unrelated to the ternary operator, the above example assigns a name to the lambda expression. Therefore, automatic checking tools such as Python's coding convention PEP8 may generate a Warning.
This is because PEP8 recommends the use of def when assigning names to functions.
The concept of PEP8 is as follows
- Lambda expressions are used to pass callable objects as arguments, for example, without naming them
- In lambda expressions, use def to define by name