Simplify Chained Comparison
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python lets you write comparisons the same way you would on a whiteboard: a < b < c instead of a < b and b < c. This feature, called chained comparison, makes range checks and ordering assertions shorter and easier to read. It also avoids evaluating the middle expression twice, which matters when that expression is a function call with side effects. This article explains how Python evaluates chained comparisons under the hood, demonstrates practical examples, and contrasts the behavior with other popular languages.
How Python Evaluates Chained Comparisons
When Python encounters a < b < c, it does not treat it as (a < b) < c. Instead it rewrites it internally as:
with the important guarantee that b is evaluated only once. If the first comparison is False, Python short-circuits and never evaluates c at all.
Here is a concrete demonstration:
You can chain more than two operators:
Mixing Different Operators
Chained comparisons are not limited to <. You can mix any comparison operators, including <=, >=, ==, !=, is, is not, in, and not in. Each adjacent pair is joined by an implicit and.
Range Checks in Practice
The most common use case is validating that a value falls inside a range:
Without chaining you would write temp >= 20 and temp < 30, which repeats temp and is slightly harder to scan.
Single Evaluation of the Middle Expression
Because the middle operand is evaluated only once, chaining is safer when the expression has side effects:
Contrast with Other Languages
Most languages do not support chained comparisons. In JavaScript, C, C++, and Java, writing 1 < x < 10 compiles and runs, but it does not do what you might expect:
JavaScript first evaluates 1 < x to true, then coerces true to 1 and compares 1 < 10, which is true even though x is 15. The correct JavaScript equivalent is:
Ruby and Rust also require the explicit && form. Among mainstream languages, Python is nearly unique in supporting mathematical-style chaining natively.
Common Pitfalls
- Assuming other languages support chaining. Writing
a < b < cin JavaScript or C produces a valid but semantically incorrect expression because the boolean result of the first comparison is coerced to a number before the second comparison. - Chaining
!=and expecting "all different." The expressiona != b != cmeans(a != b) and (b != c), which does not check whethera != c. To verify all three are distinct, you need an explicit check or uselen({a, b, c}) == 3. - Overcomplicating chains with too many operators. A chain like
a < b >= c != d is not eis technically valid but unreadable. Limit chains to straightforward range checks for clarity. - Forgetting short-circuit behavior in chains with side effects. If the first comparison is
False, subsequent expressions in the chain are never evaluated. Code that relies on those expressions executing (for example, function calls that update state) will silently skip them. - Using chained comparisons with incompatible types. In Python 3, comparing unorderable types (like
intandstr) raises aTypeError. A chain like0 < "hello" < 10will fail at the first comparison, and the error message may be confusing if you are not expecting it.
Summary
- Python chained comparisons rewrite
a < b < casa < b and b < cwithbevaluated only once. - You can mix any comparison operators (
<,<=,==,!=,is,in, and others) in a single chain. - Short-circuit evaluation means later parts of the chain are skipped as soon as one comparison is
False. - Most other languages (JavaScript, C, Java) do not support this syntax; they coerce the boolean result of the first comparison and produce incorrect results.
- Keep chains simple -- one or two operators for range checks -- and avoid long chains that sacrifice readability.
Related reading
- simultaneously update theta0 and theta1 to calculate gradient descent in python
- Single quotes vs. double quotes in Python
- Skip first entry in for loop in python?
- Sklearn cross_val_score with multi input KerasClassifier
- sklearn doesn't have attribute 'datasets
- SKLearn how to get decision probabilities for LinearSVC classifier
- sklearn How to reset a Regressor or classifier object in sknn
- sklearn ImportError cannot import name plot_roc_curve
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.