Python — Chained comparisons and short-circuit operators
Python can chain comparisons and use and to guard a later lookup. If the range check fails, the list access is skipped.
A simple example
Test two conditions
- Start with n is 2
- Do this Greater than 0 and less than 3?
- Result yes
n = 2
if n > 0 and n < 3:
print("yes")
yes
Operator examples
| Operation | Expression | Result |
|---|---|---|
| Floor division | 7 // 2 |
3 |
| True division | 7 / 2 |
3.5 |
| Remainder | 7 % 2 |
1 |
| Chained comparison | 0 <= 1 < 2 |
True |
| Equality | 3 == 4 |
False |
| Logical conjunction | True and False |
False |
Guard an indexed lookup
Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. A negative Python list index can refer to an element from the end. The explicit lower bound enforces this report's zero-based index contract.
A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.
Run the example
Use Python 3.9 or later. Run these commands from the directory containing the example.
python3 lesson.py
stock = [2, 5]
for index in (-1, 1, 2):
take = 0 <= index < len(stock) and stock[index] >= 5
print("take" if take else "skip")
skip take skip
Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.
Try it yourself
Try index 0, then change its value from 2 to 5. How does its classification change?
Check your answer
Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.