Sub topic 4
Chained comparisons
This chapter covers how Python reads several comparison operators written in a row, such as 1 < x <= 10. It assumes you know basic Python syntax, the built-in types int, str, list and dict, and the comparison operators from the previous chapter. It also assumes you know that and and or short-circuit.
What a chain is
A chained comparison puts two or more comparison operators in one expression. Python reads the chain as a series of pairwise comparisons joined by and.
x = 5
print(1 < x <= 10) # True
print(1 < x < 3) # False
print("apple" < "banana") # True
print([1, 2, 3] == [1, 2, 3]) # True1 < x <= 10 means 1 < x and x <= 10. The chain is true only if every link is true. Each neighbouring pair of operands is compared with the operator between them.
The general rule: a op1 b op2 c behaves like a op1 b and b op2 c, except that b is evaluated only once.
| Chain | Equivalent expansion |
|---|---|
| `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` | `a < b and b > c` |
| `a < b < c < d` | `a < b and b < c and c < d` |
The chain can be as long as you like. The two operators need not point the same way, and the operands need not be numbers. Any values that support the operators work.
Which operators can be chained
All of these comparison operators share one precedence level and chain with each other:
<,<=,>,>===,!=is,is notin,not in
Because the whole group chains, you can write combinations that look odd. a is b is c and x in y in z are valid. They are rarely a good idea, and a few of them behave in ways that surprise people (see the gotchas below).
Operators that bind more tightly than comparisons are evaluated first. For example, in 0 < x + 1 < 10 the additions happen before any comparison. Operators that bind more loosely, not, and and or, apply after the whole chain is resolved.
x = 5
print(not 1 < x < 3) # True: not (1 < x < 3)
print(1 < x < 10 and x != 7) # TrueThe middle operand is evaluated once
This is the main difference between a chain and a hand-written and. In a < b < c, the expression b runs one time. That matters when b is a function call, has side effects, or is expensive to compute.
def show(label, value):
print("evaluating", label)
return value
print(1 < show("middle", 5) < 10)
# evaluating middle
# True
print(1 < show("middle", 5) and show("middle", 5) < 10)
# evaluating middle
# evaluating middle
# TrueThe chain calls show once. The and version calls it twice. If b returned a different value on each call, such as a random number or a reading from a sensor, the two forms could even give different answers.
Chains short-circuit
A chain stops at the first link that is false. Operands to the right of that link are never evaluated.
def show(label, value):
print("evaluating", label)
return value
print(5 < 3 < show("never", 10))
# FalseNothing is printed by show, because 5 < 3 is already false. Python does not evaluate show("never", 10) at all.
The following diagram shows the evaluation order for a < b < c.
What a chain returns
For built-in types, every comparison returns a bool, so the chain returns a bool. For your own classes, a comparison method such as __lt__ can return any object. A chain tests each intermediate result for truthiness and stops at the first falsy one. It returns whichever result it stopped on, which is the first falsy result or the last result.
class Probe:
def __init__(self, name, result):
self.name = name
self.result = result
def __lt__(self, other):
print(f"{self.name} < {other.name}")
return self.result
b = Probe("b", "second ok")
c = Probe("c", "unused")
print(Probe("a", "first ok") < b < c)
# a < b
# b < c
# second ok
print(Probe("a", 0) < b < c)
# a < b
# 0In the first call, the result of a < b is the non-empty string "first ok", which is truthy, so the chain continues. The chain then returns the result of b < c, which is "second ok". In the second call, the first link returns 0, which is falsy. The chain returns 0 and never calls b < c.
This is the same rule you saw for and: the result is one of the operands, not necessarily True or False. It is why libraries whose comparisons return arrays, such as NumPy, cannot use chains. 0 < arr < 5 forces Python to ask whether the array result is true, and that raises an error.
Typical uses
Chains read like the mathematical notation they imitate. The most common uses are range checks and equality of several values.
def valid_index(i, items):
return 0 <= i < len(items)
def is_lowercase_letter(ch):
return "a" <= ch <= "z"
def all_equal(a, b, c):
return a == b == c
print(valid_index(2, [10, 20, 30])) # True
print(valid_index(3, [10, 20, 30])) # False
print(is_lowercase_letter("m")) # True
print(all_equal(4, 4, 4)) # True0 <= i < len(items) is the standard pattern for a half-open range. It includes the lower bound and excludes the upper one, which matches how range and slicing work.
Gotchas
Chains that do not mean what they look like
!= only compares neighbours. It does not test that all values differ.
print(1 != 2 != 1) # TrueThis expands to 1 != 2 and 2 != 1. The first and third values are equal, but the chain never compares them. To test that three values are all different, compare every pair or compare len({a, b, c}) == 3, which works for hashable values.
Mixed directions are legal but hard to read. 1 < x > 3 means 1 < x and x > 3, which does not compare 1 and 3 at all. If a reader has to stop and work out which pairs are compared, write the and explicitly.
Mixing in `in` and `is`
Because in and is belong to the same chain family, they chain too.
print(False == False in [False]) # TrueThis is False == False and False in [False], which is True and True. It is not (False == False) in [False], which would also be true here but for a different reason. Chains that mix ==, in and is are a known source of bugs. Prefer one operator type per chain.
Parentheses break the chain
Adding parentheses turns a chain into two separate comparisons, and the inner result becomes an operand.
print(3 > 2 > 1) # True: 3 > 2 and 2 > 1
print((3 > 2) > 1) # False: True > 1, which is 1 > 1Here you see bool behaving as an int: True is equal to 1. Parentheses are almost never what you want inside a range check.
Operands that cannot be ordered
A chain fails when any link it actually evaluates fails. None has no ordering with numbers, so a range check on a missing value raises TypeError instead of returning False.
value = None
try:
print(0 < value < 10)
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'int' and 'NoneType'If value can be None, test that first: value is not None and 0 < value < 10.
Not-a-number values behave differently. They do not raise an error. Every ordering comparison with float("nan") is false, so 1 < float("nan") < 3 is False.
nan = float("nan")
print(1 < nan < 3) # False
print(nan == nan) # FalseA chain is not a replacement for `or`
A common beginner error is x == 1 or 2, which is always truthy because 2 is truthy on its own. A chain does not fix this. For "x is one of several values" use x in (1, 2).
When to use a chain
Use a chain when it reads as one idea: a value lies between two bounds, or several values are equal. Write the explicit and when the pairs being compared are not neighbours in a natural order, when the operators differ in kind, or when the expression needs a comment to explain it. Both forms are correct, so choose the one a colleague can read in a second.
Exercise
What do print(2 < 3 > 1 != 1) and print(1 != 2 != 1) print, and why?
Show answer
The first prints False and the second prints True. The first chain expands to 2 < 3 and 3 > 1 and 1 != 1, and the last link is false. The second expands to 1 != 2 and 2 != 1, and both links are true. Chained != compares only neighbouring operands, so it never compares the first and third values.
Exercise
A function read_level() returns a number between 0 and 100, or None if the sensor is offline. Write a condition that is true only when the level is a number from 20 up to, but not including, 80, calls read_level() only once, and never raises TypeError.
Show answer
Store the result first: level = read_level(), then test level is not None and 20 <= level < 80. The is not None check short-circuits before the ordering comparison, so None never reaches <=. Storing the result in a variable means the function runs once, which a chain would also guarantee for a middle operand, but here the value is needed on both sides of the and.