Chained Comparisons
Concepts covered: Boolean Operators
Python allows you to chain comparison operators in a way that reads naturally. Instead of writing x > 5 and x < 10, you can write 5 < x < 10. This matches how you would express ranges in mathematics and makes your code more readable.
Basic chained comparisons
You can chain any comparison operators together. Python evaluates them left to right, and all comparisons must be true for the entire expression to be true:
x = 15
# Instead of: x > 10 and x < 20
if 10 < x < 20:
print(x, "is between 10 and 20 (exclusive)")
# Instead of: x >= 10 and x <= 20
if 10 <= x <= 20:
print(x, "is between 10 and 20 (inclusive)")
# Chain more than two comparisons
y = 5
if 0 < y < 10 < x < 20:
print("Both y and x are in their expected ranges")
# Works with variables on all sides
low = 10
high = 20
if low < x < high:
print(x, "is between", low, "and", high)Output:
15 is between 10 and 20 (exclusive) 15 is between 10 and 20 (inclusive) Both y and x are in their expected ranges 15 is between 10 and 20
The expression 10 < x < 20 is equivalent to 10 < x and x < 20, but shorter and more readable. Python evaluates x only once.
Chained comparisons are especially useful in data validation, where you frequently need to confirm values fall within acceptable ranges:
- a < x < b: Value between, not equal
- a <= x <= b: Value between or on edge
- a == b == c: Every value is identical
- a < b < c: Values are ascending left
Range checking
Range checks are where chained comparisons show up most:
def validate_percentage(value):
"""Validate percentage."""
if 0 <= value <= 100:
return "Valid percentage"
return "Invalid: must be 0-100"
def validate_age(age):
"""Validate age."""
if 0 < age < 150:
return "Valid age"
return "Invalid age"
def categorize_temperature(temp):
"""Categorize temperature."""
if temp < 32:
return "freezing"
elif 32 <= temp < 50:
return "cold"
elif 50 <= temp < 70:
return "cool"
elif 70 <= temp < 85:
return "warm"
else:
return "hot"
print(validate_percentage(75))
print(validate_percentage(150))
print(categorize_temperature(65))Output:
Valid percentage Invalid: must be 0-100 cool
Chaining equality operators
You can also chain equality operators, which is useful for checking if multiple values are equal:
a = 5
b = 5
c = 5
# Check if all three are equal
if a == b == c:
print("All three values are equal")
# Check if sorted in order
x = 1
y = 2
z = 3
if x < y < z:
print("Values are in ascending order")
if x <= y <= z:
print("Values are in non-descending order")
# Mix of operators
score = 85
if 80 <= score < 90:
print("Grade: B")Output:
All three values are equal Values are in ascending order Values are in non-descending order Grade: B
Chained comparisons are especially easy to get wrong when combining inequality operators. The safest approach is to read the chain aloud as a mathematical expression: "Is value at least 0 and at most 100?" maps directly to "0 <= value <= 100".
When the valid range is clear, an else clause handles everything outside it without needing a second chained comparison. Trying to express the invalid range as its own chain often leads to a condition that can never be satisfied.
Chained comparisons only work in one direction. Python evaluates a < x < b left to right, so a < x and x < b. If you reverse the direction inconsistently, like a < x and x >= b combined, you may accidentally overlap or leave gaps in your range logic.
About this lesson
This section is part of the Control Flow: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.