Use Python’s chained comparison syntax low <= x <= high (for an inclusive range) or low < x < high (for a strictly exclusive range), which evaluates both bounds natively in C without creating intermediate objects and short-circuits immediately if the first comparison fails.
Basic Example
x = 15
low, high = 10, 20
# 1. Recommended (inclusive bounds: 10 <= x <= 20):
if low <= x <= high:
print(f"{x} is within [{low}, {high}]")
# Output: 15 is within [10, 20]
# 2. Strictly exclusive bounds (10 < x < 20):
print(10 < x < 20) # Output: True
print(10 < 10 < 20) # Output: False
# 3. Half-open range (standard Python indexing convention: low <= x < high):
print(10 <= 20 < 20) # Output: False
Key Details & Edge Cases
- Chained comparisons evaluate the middle expression (
x) only ONCE:low <= get_score() <= highcallsget_score()a single time and automatically short-circuits (skipping<= high) iflow <= scoreisFalse—making it both faster and side-effect-safe compared to writing(low <= get_score()) and (get_score() <= high).
- Why
low <= x <= highbeatsx in range(low, high + 1):- Works with floats and
Decimals:x in range(10, 21)returnsFalseforx = 15.5(becauserangecontains only integers), whereas10 <= 15.5 <= 20works for any comparable numeric type (int,float,Decimal,Fraction,date). - No
high + 1off-by-one bug:range(low, high)excludeshighby default, forcing an error-prone+ 1for inclusive bounds. - Faster execution: Although
int in range(...)runs in $O(1)$ time in Python 3, constructing arangeobject still incurs function-call and object-allocation overhead compared to direct bytecode comparison operators (COMPARE_OP).
- Works with floats and
- Unknown bound ordering (
min(a, b) <= x <= max(a, b)):- If
lowmight be greater thanhigh(for example,low = 20, high = 10),20 <= 15 <= 10evaluates toFalse. Normalize unordered bounds first withmin(a, b) <= x <= max(a, b).
- If
- Vectorized range checks across NumPy arrays or Pandas Series:
- Python’s chained
low <= arr <= highraisesValueError: The truth value of an array/Series is ambiguouson NumPy arrays and Pandas Series. Use(low <= arr) & (arr <= high)in NumPy ordf["col"].between(low, high)in Pandas instead.
- Python’s chained
Comparison of Numeric Range-Checking Methods in Python
| Method | Syntax | Supports float / Decimal? |
Inclusive of Upper Bound? | Works on NumPy / Pandas? | Best Used When |
|---|---|---|---|---|---|
| Chained Comparison (Recommended) | low <= x <= high |
Yes | Yes (use < for exclusive) |
No (ValueError) |
Checking any single int, float, Decimal, or date against bounds. |
range() Membership |
x in range(low, high + 1) |
No (15.5 in range(...) is False) |
No (requires + 1) |
No | Checking whether an integer is a valid zero-based sequence index (0 <= i < len(seq)). |
Pandas .between() |
df["col"].between(low, high) |
Yes | Yes (inclusive="both"/"neither") |
Yes (Pandas Series) |
Filtering rows inside a Pandas DataFrame by a numeric or date range. |
NumPy Bitwise |
(low <= arr) & (arr <= high) |
Yes | Yes | Yes (NumPy ndarray) |
Creating boolean masks over 1D/N-D NumPy arrays. |
You must log in or register to comment.
