Python for Programmers: Ternaries
Welcome to the Ternaries lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Python has a second conditional syntax:
value1 if condition else value2. Ifconditionis true, it evaluates tovalue1. Otherwise it evaluates tovalue2.>
1 if True else 2Result:
1
>
1 if False else 2Result:
2
These are called ternary expressions. (Ternary means "composed of three parts". Here, the three parts are the true value, the condition, and the false value.)
You might be familiar with C-style ternaries:
condition ? value1 : value2. Python's ternaries use less punctuation, as usual, and the order is different. But the basic idea is the same.Ternaries are useful in many situations, but their most notable use case is in lambdas. We've seen that lambda functions can only contain expressions, not statements.
ifis a statement, so we can't use it in a lambda. However, we can use a ternary.>
positive_or_zero = lambda x: x if x >= 0 else 0- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
positive_or_zero(15)Result:
15
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
positive_or_zero(-2)Result:
0
It's important to use ternaries sparingly. Chaining them can make code difficult to read.
>
# This function "clamps" a value, ensuring that it's between 0 and 10# (inclusive).clamp = lambda x: 10 if x > 10 else 0 if x < 0 else x- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
clamp(4)Result:
4
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
clamp(-10)Result:
0
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
clamp(103)Result:
10
We can try to make that expression more readable by adding some newlines and parentheses.
>
clamp = lambda x: (10 if x > 10else (0 if x < 0else x))[clamp(4), clamp(-10), clamp(103)]Result:
At that point, it's better to give up on the lambda. A regular
defandifare only slightly longer, but they're much easier to read.>
def clamp(x):if x > 10:return 10elif x < 0:return 0else:return x[clamp(4), clamp(-10), clamp(103)]Result: