Guide Python Intermediate

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.

2 min read

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. Reserve is strictly for identity checks — most commonly x 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 is instead of == for value comparison, which can silently appear correct thanks to CPython’s small-integer caching and string interning; confusing / (always returns float) with // (floors to a whole number), especially when porting from Python 2; and misjudging operator precedence in a mixed expression, like assuming and binds tighter than == when it’s actually the other way around.”

Common Mistakes

  • Trusting is to “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 an int — it returns a float if either operand is a float (e.g. 5.0 // 2 is 2.0, not 2).
  • 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