all Python 3Arithmetic & operatorsterm
Chained comparisons
comparison
Python lets you write several comparisons in a row in one expression. 1 < x < 10 is equivalent to (1 < x) and (x < 10) and is evaluated left to right.
Syntax
a < b < c a == b == c a <= b >= c
The middle operand is evaluated exactly once, and the chain short-circuits: if the first comparison is false, the second is never run. Hence the classic trap — x != y != z does not mean all three differ, it only checks neighbouring pairs, so x and z may well be equal.
Examples
x = 5
print(1 < x < 10) # → True
print(1 < x < 4) # → False
print(1 == 1 == 1) # → True
print(1 == 1 == 2) # → False
print(0 <= x <= 100) # → True
print(10 > x > 0) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy