Guide Python Intermediate

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.

2 min read

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 < c directly instead of (a < b) and (b < c). Internally, that’s exactly how it’s evaluated — as an implicit and between 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, like 400 <= status_code < 500 to check an HTTP status code falls in the client-error range.”

Common Mistakes

  • Believing a < b < c evaluates b twice, once for each comparison — it’s evaluated exactly once and reused.
  • Writing a < b and c < d when the intent was actually a < 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 == c and mixed chains like a < b == c are both valid.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form