7.14 Common Mistakes
The most common operator-related bugs in Python — using is instead of ==, confusing / with //, and misreading mixed comparison/logical expressions due to precedence.
Using is Instead of ==
What Goes Wrong?
is compares identity, not value — it can appear to work for small integers or short strings, due to CPython’s caching/interning (see 6.7 Memory Optimization), and then mysteriously fail for larger or dynamically-constructed values.
>>> a = 1000
>>> b = int("1000") # parsed at runtime -- a genuinely separate object
>>> a == b # correct way to compare VALUES
True
>>> a is b # unreliable -- False here, though it might look True
False # with small cached ints in other examples
Rule: Always use
==to compare values. Reserveisstrictly for identity checks — most commonlyx is None.
Division Mistakes
Confusing / (always float) with // (floored, often int-like) — especially easy to trip over when porting logic from Python 2, where / used to behave like // for two ints.
>>> 5 / 2 # true division
2.5
>>> 5 // 2 # floor division
2
Operator Precedence Issues
Assuming an expression groups the way intended without checking precedence — easy to misread a mixed comparison/logical expression:
>>> result = 2 + 3 == 5 and 1 < 2 # arithmetic and comparisons happen before 'and'
>>> result # equivalent to: ((2+3) == 5) and (1 < 2)
True
Quick Interview Answer
“The three recurring operator bugs are: using
isinstead of==for value comparison, which can silently appear correct thanks to CPython’s small-integer caching and string interning; confusing/(always returnsfloat) with//(floors to a whole number), especially when porting from Python 2; and misjudging operator precedence in a mixed expression, like assumingandbinds tighter than==when it’s actually the other way around.”
Common Mistakes
- Trusting
isto “work” in testing with small literal values, then shipping code that breaks on larger or runtime-constructed values — see 7.8 Identity Operators. - Assuming
//always produces anint— it returns afloatif either operand is afloat(e.g.5.0 // 2is2.0, not2). - Skipping parentheses in a mixed expression “because it’s obvious,” then having a teammate (or future self) misread it exactly the way the precedence rules predict.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form