Sub topic 9
Chained comparisons such as 0 <= x < 10
This chapter assumes you can write a basic if statement and use comparison operators like <, >=, and ==. It also assumes you know that and combines two conditions. Here you will learn how Python lets you write a range test as one expression.
The range test in one expression
Many languages make you write a range check with and:
x = 7
if 0 <= x and x < 10:
print('single digit')Python lets you write the same test the way you would on paper. This is a chained comparison:
x = 7
if 0 <= x < 10:
print('single digit')
if x in (1, 3, 5, 7, 9):
print('odd single digit')The first if prints single digit because both parts of the chain are true. The second if uses in to test membership in a tuple. Use a chain for a continuous range and in for a fixed set of values.
What a chain really means
a < b < c is not evaluated as (a < b) < c. Python treats it as a < b and b < c, with one difference: b is evaluated only once.
The chain also short-circuits. If the first comparison is false, Python never runs the second one. Evaluating the middle value once matters when it is a function call:
def read_sensor():
print('reading sensor')
return 21.5
if 18 <= read_sensor() <= 25:
print('comfortable')This prints reading sensor once, then comfortable. If you wrote 18 <= read_sensor() and read_sensor() <= 25, the sensor would be read twice. The two readings could differ, which is a subtle bug.
Mixing operators
A chain can use any comparison operators, including ==, !=, in, and is. It can also be longer than three parts:
a, b, c = 5, 5, 5
if a == b == c:
print('all equal')
low, mid, high = 1, 5, 9
if low < mid < high:
print('strictly increasing')Each neighboring pair is tested, and every test must pass.
Gotchas
Chains compare only neighbors. A chain such as a < b > c is legal, but it never compares a with c:
a, b, c = 1, 9, 5
print(a < b > c) # True: 1 < 9 and 9 > 5
print(a < c) # True, but the chain did not test thisChains with mixed directions are hard to read, so use and for them. Another gotcha is x == y != z. It means x == y and y != z, which is not the same as x == y and x != z in every case you might expect. When a reader has to stop and decode a chain, switch to explicit and.
Do not write 0 <= x < 10 as 0 <= x and < 10, or as x >= 0 and <10. Each side of and must be a complete comparison.
Also remember that range ends are inclusive or exclusive depending on the operator. 0 <= x < 10 accepts 0 through 9, which matches how range(0, 10) behaves.
Practice
Exercise
What does this code print, and how many times does get() run?
def get():
print('get')
return 3
print(1 < get() < 3)
Show answer
It prints get once, then False. The chain means 1 < get() and get() < 3, but get() is evaluated only once. The value 3 passes 1 < 3 but fails 3 < 3, so the result is False.