Python Ternary Operator
By Flavio Copes
Learn how to use the ternary operator in Python to write a conditional in a single line, using the result if true if condition else result if false syntax.
The ternary operator in Python allows you to quickly define a conditional in a single line. You write the value for the true case, then the condition, then the value for the false case.
Let’s say you have a function that compares an age variable to the 18 value, and return True or False depending on the result.
Instead of writing:
def is_adult(age):
if age > 18:
return True
else:
return False
You can implement it with the ternary operator in this way:
def is_adult(age):
return True if age > 18 else False
First you define the result if the condition is True, then you evaluate the condition, then you define the result if the condition is false:
<result_if_true> if <condition> else <result_if_false>
Notice the order. The condition sits in the middle, but Python evaluates it first, then picks one of the two sides.
In this specific case you could return the comparison directly, with return age > 18. The ternary operator earns its place when the two results are different values, not just True and False.
Where the ternary operator shines
The most common use is assigning one of two values to a variable:
temperature = 25
label = 'warm' if temperature > 20 else 'cold'
print(label) # warm
Compare that to four lines of if/else. When the choice is this small, the one-liner reads better.
Only one branch runs
Python evaluates only the side it picks. The other expression never runs:
count = 0
total = 0
average = total / count if count > 0 else 0
print(average) # 0
Here count is zero, so the condition is False and Python returns 0 directly. The division never executes, and you get no ZeroDivisionError. You can use the ternary operator to guard against exactly this kind of problem.
A pitfall: nesting
You can chain ternary operators, but readability suffers fast:
temperature = 25
label = 'hot' if temperature > 30 else 'warm' if temperature > 20 else 'cold'
print(label) # warm
This works. Python checks the first condition, and when it’s False it moves on to the next ternary. But you have to read the line twice to be sure of what it does.
My advice: use the ternary operator for one condition and two outcomes. The moment you need a third branch, switch to a regular if/elif/else block.
Related posts about python: