Sub topic 6
Chained comparisons
This chapter assumes you know basic Python syntax, the core types int and float, and the single comparison operators <, <=, >, >=, == and !=.
What a chain means
Python lets you write several comparisons in a row. The chain a < b < c means a < b and b < c. It is not read as (a < b) < c, which would compare a bool to a number.
x = 5
print(1 < x < 10)
print(1 < x < 3)The first line prints True. The second prints False, because 1 < 5 holds but 5 < 3 does not.
How evaluation works
A chain follows two rules:
- The middle operand is evaluated once, even though it takes part in two comparisons.
- Evaluation stops at the first comparison that is false.
def read():
print("read called")
return 5
def right():
print("right evaluated")
return 10
print(1 < read() < 10)
print(5 < 3 < right())The first print shows read called once, then True. The second prints only False. The first comparison, 5 < 3, fails, so right() never runs.
Mixing operators
A chain can combine different comparison operators, and it can be longer than three operands. Each neighbouring pair is compared, and all the comparisons must be true.
print(3 > 2 > 1)
print(1 == 1 < 2)
print(1 < 2 > 1.5)
print(0 <= 5 < 10 <= 10)All four lines print True. The third line shows that 1 and 1.5 are never compared with each other.
Common errors
The most common mistake is reading a chain as a statement about all its operands. Only neighbouring pairs are compared.
print(1 != 2 != 1)This prints True. It means 1 != 2 and 2 != 1, so the first and last values are never compared. Do not use it to check that three values are all different.
Chains with is, in and not in follow the same rule, because these are comparison operators too. For example, a == b is None means a == b and b is None. That is rarely what the author meant.
When to use a chain
A chain is the clearest way to test that a value lies within a range. It is shorter than low <= x and x < high, and it evaluates x only once. That matters when x is a function call or has side effects.
| Written as | Means |
|---|---|
| `a < b < c` | `a < b and b < c` |
| `a <= b < c` | `a <= b and b < c` |
| `a == b == c` | `a == b and b == c` |
Exercise
What does print(2 < 3 > 1 < 0) print, and which comparisons are performed?
Show answer
It prints False. Python checks 2 < 3 (True), then 3 > 1 (True), then 1 < 0 (False). The chain is false because the last comparison fails.