7.12 Chained Comparisons
How Python evaluates chained comparisons like a < b < c internally, why the middle value is only evaluated once, and range-validation use cases.
Syntax
Python allows writing a < b < c directly, unlike languages where you’d need (a < b) and (b < c) explicitly.
>>> x = 5
>>> 1 < x < 10
True
Evaluation
What Happens Internally?
a < b < c is evaluated as (a < b) and (b < c), with b evaluated only once even though it appears twice logically — important if b were an expensive expression or had side effects.
>>> 1 < x < 10 < 20
True
Use Cases
Extremely common for range validation — checking a value falls within bounds in one readable line:
status_code = 404
>>> 400 <= status_code < 500 # is it a client error?
True
Quick Interview Answer
“Chained comparisons let Python express
a < b < cdirectly instead of(a < b) and (b < c). Internally, that’s exactly how it’s evaluated — as an implicitandbetween each adjacent pair — with one subtlety: the shared middle value (b) is only evaluated once, which matters if it’s an expensive call or has side effects. The most common real use is range validation, like400 <= status_code < 500to check an HTTP status code falls in the client-error range.”
Common Mistakes
- Believing
a < b < cevaluatesbtwice, once for each comparison — it’s evaluated exactly once and reused. - Writing
a < b and c < dwhen the intent was actuallya < b < c < d— different chains produce very different logic, easy to typo under time pressure. - Not realizing chained comparisons work with any comparison operator, not just
<—a == b == cand mixed chains likea < b == care both valid.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form