Sub topic 6
Chained comparisons
This chapter assumes you know the basic comparison operators (<, <=, >, >=, ==, !=) and that and/or combine boolean values. It covers how Python expands a chain of comparisons, when the middle operands are evaluated, and which chains read differently from what they look like.
What a chain is
Python lets you write several comparison operators in one expression. A range check then reads like it does in mathematics:
x = 5
print(1 < x < 10)
print(1 < x < 3)The first line prints True and the second prints False. The expression 1 < x < 10 means 1 < x and x < 10, with one difference: x is evaluated only once.
The general rule is that a op1 b op2 c is equivalent to a op1 b and b op2 c. The same rule extends to any length.
| Chain | Equivalent expression |
|---|---|
| `a < b < c` | `a < b and b < c` |
| `a <= b < c` | `a <= b and b < c` |
| `a == b == c` | `a == b and b == c` |
| `a < b < c < d` | `a < b and b < c and c < d` |
Note that a and c are never compared with each other. Python only compares neighbouring pairs.
Single evaluation of middle operands
When the middle operand is a variable, evaluating it once or twice makes no visible difference. When it is a function call, it does:
def read_value():
print("read_value called")
return 5
print(1 < read_value() < 10)
print(1 < read_value() and read_value() < 10)The first print shows one read_value called line and then True. The second shows two call lines and then True. For middle operands that are slow, have side effects, or return different values on each call (reading a sensor, popping from a queue), the chained form is both faster and safer.
Chains short-circuit
A chain stops at the first comparison that is false. Operands to the right of that point are not evaluated at all.
def probe(label, value):
print("evaluating", label)
return value
print(probe("a", 5) < probe("b", 3) < probe("c", 9))The output is:
evaluating a
evaluating b
FalseThe comparison 5 < 3 is false, so probe("c", 9) never runs. This matches how and behaves, which a later chapter covers in detail.
Practical uses
The most common use is a range or bounds check:
def in_bounds(index, items):
return 0 <= index < len(items)
data = [10, 20, 30]
print(in_bounds(2, data))
print(in_bounds(3, data))
print(in_bounds(-1, data))
print("a" <= "m" <= "z")This prints True, False, False, True. Mixing <= and < is useful for half-open ranges, where the lower bound is included and the upper bound is not. That is the same convention range() and slicing use.
Equality chains are also valid:
a = b = c = 4
print(a == b == c)This prints True. It is a compact way to assert that several values agree.
Chains are not limited to ordering operators
Every comparison operator can take part in a chain. That includes ==, !=, is, is not, in and not in. Mixed directions are legal:
print(1 < 5 > 3)
print(1 != 2 != 1)Both lines print True. The first means 1 < 5 and 5 > 3. The second means 1 != 2 and 2 != 1. It does not mean the three values are all different, because 1 and the last 1 are never compared.
Gotchas
Parentheses change the meaning
A chain exists only when the comparisons are not parenthesized. Adding parentheses compares a boolean with the next value instead:
print(5 > 3 > 1)
print((5 > 3) > 1)The first line prints True. The second prints False, because (5 > 3) becomes True, and True > 1 compares 1 > 1. Booleans are integers in Python, so this does not raise an error. It simply gives a surprising answer.
Membership and identity inside a chain
Since in and is are comparison operators, they chain too, which can turn an intended single test into two:
print(1 in [1, 2] == True)This prints False. It expands to 1 in [1, 2] and [1, 2] == True. The first part is true, but a list never equals True, so the whole chain is false. If you meant to test membership and then compare the result, write the parentheses explicitly. Usually the better fix is to drop the extra comparison, since 1 in [1, 2] is already a boolean.
Not the same as other languages
In C, Java and JavaScript, 1 < x < 10 is read as (1 < x) < 10. The inner comparison gives true or false, which is converted to 1 or 0, and that is always less than 10. So the expression is always true there, whatever x is. Python's chaining removes this trap, but keep it in mind when translating code between languages.
Values whose comparisons are not booleans
Python joins the pieces of a chain with the truth value of each comparison. A chain therefore fails when a comparison returns something that has no single truth value. NumPy arrays are the usual example: 0 < arr < 5 raises a ValueError, because 0 < arr produces an array of booleans and Python cannot decide whether that array is true or false. Write (0 < arr) & (arr < 5) for arrays instead.
Floating-point nan values behave as you would expect from the rule above. Every ordering comparison with nan is false, so the chain stops there:
nan = float("nan")
print(1 < nan < 10)This prints False.
Chains do not replace `or`
A chain only combines comparisons with an implicit and. It cannot express "equal to one of these values". The expression x == 1 or 2 is a separate common mistake: it parses as (x == 1) or 2, which is always truthy. Use x in (1, 2) for that test.
When to use a chain
Use a chain when it reads as a single mathematical statement about one value: lo <= x <= hi, 0 <= i < n, a == b == c. Switch to explicit and when the comparisons involve different subjects, or when mixed operators such as is, in and != would make the reader stop and work out the grouping. Short chains of two comparisons are the sweet spot, and chains of four or more are rarely clearer than and.
Exercise
What do print(3 > 2 > 2) and print(0 == 0 != 1) print, and why?
Show answer
The first prints False. It expands to 3 > 2 and 2 > 2, and the second part is false. The second prints True. It expands to 0 == 0 and 0 != 1, and both parts are true.
Exercise
In 1 < f() < 10, how many times is f called when its result is 20? How many times is f called in 1 < f() and f() < 10?
Show answer
The chained form calls f once. The result is 20, so 1 < 20 is true and 20 < 10 is false, and the chain returns False. The and form calls f twice, because each f() is a separate expression, and it also returns False.