How do Python's chained comparisons work, and how do they differ from the same expression in most other languages?
Answer
Python evaluates `a < b < c` as `a < b and b < c`, with `b` evaluated only once, short-circuiting to False as soon as either comparison fails. In many other languages `a < b < c` would evaluate left to right as `(a < b) < c`, comparing a boolean to `c`, which produces a confusing and usually meaningless result. Python's version reads naturally like mathematical notation and is idiomatic for range checks.
Strong answer includes
- equivalent to a < b and b < c
- middle operand evaluated once, short-circuits
- different from left-to-right boolean chaining in other languages
Practical example
if 0 <= age < 18:reads directly as a range check, equivalent to
if 0 <= age and age < 18:but without evaluating `age` twice.