Sub topic 4
Chained comparisons
This chapter assumes you can write basic Python functions and if statements, and that you know how comparison operators such as <, ==, and != produce bool values. Here you will learn how Python lets you chain several comparisons in one expression, what that expression really means, and where it can surprise you.
The idea
In many languages, checking that a number lies in a range takes two comparisons joined by a logical operator. Python lets you write the range the way you would on paper.
x = 5
print(1 < x <= 10) # True
print(1 < x < 3) # False
print("apple" < "banana") # True
print([1, 2, 3] == [1, 2, 3]) # TrueThe expression 1 < x <= 10 is a single chained comparison. It reads as "x is greater than 1 and at most 10". Strings compare in lexicographic order, which is dictionary order by character code. Lists compare element by element.
What a chain expands to
A chain a < b <= c is not evaluated as (a < b) <= c. Python treats it as:
a < b and b <= cwith one difference: b is evaluated only once. This matters when the middle operand is a function call or has side effects.
def middle():
print("middle() called")
return 5
print(1 < middle() <= 10)This prints middle() called once, then True. If you wrote the long form 1 < middle() and middle() <= 10, the function would run twice.
The chain also short-circuits. If the first comparison is false, Python skips the rest.
def noisy():
print("noisy() called")
return 100
print(10 < 5 < noisy())This prints only False, because 10 < 5 fails and noisy() is never called.
How the evaluation flows
Mixing operators
You can chain any comparison operators, including ==, !=, is, in, and their negations. Each adjacent pair is compared, and all pairs must be true.
a, b, c = 3, 3, 3
print(a == b == c) # True
x, y = 1, 2
print(x < y > 0) # True: x < y and y > 0
print(1 < 2 > 1.5) # True
print(1 == 1 != 2) # TrueBecause only adjacent pairs are compared, the first and last values are never compared directly. That can read oddly.
print(1 < 3 > 2) # True, although 1 and 2 are never compared
print(1 != 2 != 1) # True, although the first and last values are equalThe second line is a common trap. A reader may assume it means "all three are different", but 1 != 2 != 1 only checks 1 != 2 and 2 != 1. To test that all values differ, compare every pair, or compare the length of a set to the number of values.
values = [1, 2, 1]
print(len(set(values)) == len(values)) # FalseChains are not boolean arithmetic
Since comparisons return bool and bool is a kind of int, you might expect (a < b) < c to work. It does run, but it compares True or False (which act as 1 or 0) to c, which is almost never what you want.
print((1 < 2) < 3) # True, because True == 1 and 1 < 3
print(3 > 2 > 1) # True, a proper chain
print((3 > 2) > 1) # False, because True is 1 and 1 > 1 is FalseParentheses break the chain. Leave them out when you want a range test.
Common errors
- Expecting the outer values to be compared, as in
1 != 2 != 1. - Adding parentheses that turn a chain into a comparison against a
bool. - Writing long chains with mixed directions, such as
a < b > c < d. These are valid but hard to read, so split them withand. - Putting an expression with side effects in the middle and assuming it runs twice. It runs once.
Exercise
What do print(2 < 5 < 4) and print(1 == 1 != 1) print, and why?
Show answer
Both print False. In 2 < 5 < 4, the first pair 2 < 5 is true but 5 < 4 is false, so the chain is false. In 1 == 1 != 1, the first pair 1 == 1 is true but 1 != 1 is false, so the chain is false. Each chain is equivalent to joining the adjacent comparisons with and.
Exercise
Write a function in_range(value, low, high) that returns True when value is at least low and strictly less than high, using a single chained comparison.
Show answer
def in_range(value, low, high): return low <= value < high