Sub topic 9
Chained comparisons such as 0 <= x < 10
This chapter assumes you can write a basic if statement and know the comparison operators (<, <=, ==, !=, in, is) and the logical operator and. It covers how Python reads several comparisons in a row, where chaining saves effort, and the cases where it surprises people.
The working model
A chained comparison puts more than one comparison operator in a single expression:
x = 7
if 0 <= x < 10:
print('single digit')Python reads 0 <= x < 10 as two comparisons joined by and:
x = 7
chained = 0 <= x < 10
expanded = 0 <= x and x < 10
print(chained, expanded)This prints True True. The chained form matches mathematical notation, so it is easier to read. It also keeps the variable in the middle of the expression, which makes the range easy to see.
The general rule is that a op1 b op2 c means a op1 b and b op2 c. The same rule extends to any length. a < b < c < d means a < b and b < c and c < d.
Two differences from a plain `and`
The chained form is not just shorthand. It differs from the written-out and form in two ways.
The middle operand is evaluated once
In a < b < c, the expression b is computed one time, even though it takes part in two comparisons. This matters when b is a function call with a cost or a side effect:
def read_sensor():
print('sensor read')
return 42
if 0 <= read_sensor() < 100:
print('in range')The output is sensor read once, then in range. If you wrote 0 <= read_sensor() and read_sensor() < 100, the sensor would be read twice. The two reads could also return different values, so the two halves of the test might not describe the same reading.
Evaluation stops at the first false comparison
Chained comparisons short-circuit like and. Once one comparison is false, Python skips the rest, including any operands it has not evaluated yet:
def noisy(n):
print('evaluating', n)
return n
print(5 < noisy(3) < noisy(10))This prints evaluating 3 and then False. The comparison 5 < 3 fails, so noisy(10) is never called.
Choosing boundaries
The choice between < and <= at each end decides whether that end is included. Say which ends you mean before you write the test.
| Expression | Includes lower end | Includes upper end | Example values accepted |
|---|---|---|---|
| `0 <= x < 10` | yes | no | 0 to 9 |
| `0 < x <= 10` | no | yes | 1 to 10 |
| `0 <= x <= 10` | yes | yes | 0 to 10 |
| `0 < x < 10` | no | no | 1 to 9 |
The half-open form low <= x < high is the most common. It matches how range(low, high) and slicing work, and adjacent ranges such as 0 <= x < 10 and 10 <= x < 20 do not overlap or leave a gap.
Chaining in an elif chain
In an if/elif chain, earlier branches already rule out some values. The lower bound is therefore often redundant, as in the score example from the elif chapter. A full chained test is still useful when the branches are not ordered, or when you want each branch to be correct without reading the ones above it:
def bucket(n):
if 0 <= n < 10:
return 'ones'
elif 10 <= n < 100:
return 'tens'
elif 100 <= n < 1000:
return 'hundreds'
return 'out of range'
print(bucket(42))
print(bucket(-3))The output is tens and then out of range. Because each branch states its full range, you can reorder the branches without changing the result. Negative numbers fall through to the final return because no branch accepts them.
Chaining works with any comparison operator
Chaining is not limited to < and <=. It applies to every comparison operator: ==, !=, >, >=, in, not in, is, and is not. This is useful for some tests:
a, b, c = 4, 4, 4
print(a == b == c)
ch = 'm'
print('a' <= ch <= 'z')Both lines print True. The first checks that three values are equal. The second checks that a character falls in a range, using the ordering of strings. Chaining works for any types that can be compared with each other, including floats, strings, and Decimal values.
Gotchas
Mixed operators do not mean what they might look like
Python applies the rule mechanically, so the result can be surprising when the operators point in different directions or when the same value appears at both ends:
print(1 < 2 > 1)
print(1 != 2 != 1)
print(3 < 5 > 4 < 2)The output is True, True, and False.
1 < 2 > 1means1 < 2 and 2 > 1. The first and last values are never compared with each other.1 != 2 != 1isTrueeven though the first and last values are equal.a != b != cdoes not mean that all three values differ. It only says thata != bandb != c.3 < 5 > 4 < 2is3 < 5 and 5 > 4 and 4 < 2. The last comparison is false, so the whole expression is false.
Write mixed-direction chains only when the meaning is obvious to a reader. Otherwise, use and explicitly.
Parentheses stop the chaining
Python only chains comparisons that are written side by side. If you add parentheses, the inner comparison finishes first and produces a bool, and the outer comparison then uses that bool:
x = 15
print(0 <= x < 10)
print((0 <= x) < 10)The first line prints False. The second prints True, because (0 <= 15) is True, and True < 10 compares 1 < 10. No error is raised, so the mistake can go unnoticed. Do not put parentheses around part of a chain unless you want that part evaluated on its own.
Programmers who know C, Java, or JavaScript can make a similar mistake in reverse. In those languages 0 <= x < 10 is read as (0 <= x) < 10, which is nearly always true, so they must write 0 <= x && x < 10. In Python the chained form is correct and the and form is optional.
Mixed types raise an error
Every comparison in the chain must be valid. Comparing a number with a string raises TypeError as soon as Python reaches that comparison:
value = 'five'
try:
print(0 <= value < 10)
except TypeError as error:
print('TypeError:', error)The message is TypeError: '<=' not supported between instances of 'int' and 'str'. Because evaluation stops at the first false comparison, the error appears only if Python reaches the bad comparison. A chain such as 5 < 3 < 'a' returns False and never fails.
NaN makes every ordered comparison false
The float value nan ("not a number") is not less than, greater than, or equal to anything. A range check with nan therefore returns False instead of raising an error:
nan = float('nan')
print(0 <= nan < 10)
print(not 0 <= nan < 10)The output is False and True. When you test for values outside a range, remember that not 0 <= x < 10 is True for nan. The rewrite x < 0 or x >= 10 returns False for nan. The two forms are not interchangeable for this value.
When to use a chain
Use a chain when you test one value against two bounds. It is shorter than and, evaluates the middle expression once, and reads like the range you mean. Use and when the comparisons involve different values, as in a < b and c < d. Use in range(...) or a tuple only when you need a set of discrete values. For example, x in range(0, 10) is accurate for integers, but it returns False for 7.5, while 0 <= x < 10 returns True.
Exercise
What does print(3 < 5 > 4 < 2) print, and which comparison decides the result?
Show answer
It prints False. Python reads the expression as 3 < 5 and 5 > 4 and 4 < 2. The first two comparisons are true, and the last one (4 < 2) is false, so the whole expression is false.
Exercise
The variable x holds an integer. Write a condition that is true when x is between 0 and 100 inclusive but is not 50. Then write a condition that is true when x is outside the half-open range 0 <= x < 10, without using not.
Show answer
The first condition is 0 <= x <= 100 and x != 50. The second is x < 0 or x >= 10. The and is needed in the first because x != 50 is a separate test that you could not add cleanly to the same chain without making the meaning unclear. The or in the second is needed because a chain can only describe values between the bounds, not values outside them.