5.15 Common Mistakes
Three type-related mistakes that catch even experienced developers off guard — unexpected type changes, the mutable default argument bug, and comparison pitfalls.
Three type-related mistakes that catch even experienced developers off guard occasionally.
Unexpected Type Changes
Because Python is dynamically typed, reassigning a variable to a different type is silent and legal — easy to do by accident, especially after an input() call that you forgot returns str (see 4.11 Input).
Mutable Defaults
What Goes Wrong?
Using a mutable object (like []) as a function’s default argument value.
Why Is It Dangerous?
Default argument values are created ONCE, when the function is defined — not fresh on every call — so all calls that rely on the default share and accumulate into the SAME list.
>>> def add_item(item, items=[]): # BUG: mutable default
... items.append(item)
... return items
...
>>> add_item("a")
['a']
>>> add_item("b") # surprise -- 'a' is still there!
['a', 'b']
>>> def add_item_fixed(item, items=None): # FIX: use None as sentinel
... if items is None:
... items = []
... items.append(item)
... return items
...
>>> add_item_fixed("a")
['a']
>>> add_item_fixed("b")
['b']
Comparison Pitfalls
Two common traps: floating-point values that LOOK equal but aren’t exactly, due to binary representation limits; and confusing == (equal value) with is (same object).
>>> 0.1 + 0.2 == 0.3 # NOT True -- floating point imprecision
False
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b, a is b # equal VALUE, but NOT the same object
(True, False)
Quick Interview Answer
“The classic type-related gotcha is the mutable default argument: a default like
items=[]is created once at function definition time, not fresh per call, so every call that relies on it shares and accumulates into the same list — fix it withitems=Noneand create the list inside the function. The other two recurring traps are floating-point comparisons (0.1 + 0.2 != 0.3) and confusing==(value equality) withis(identity).”
Common Mistakes
- Defining a function with a mutable default argument (
def f(items=[])) instead ofNoneas a sentinel. - Comparing floats with
==for exact equality instead of a tolerance-based comparison (math.isclose()). - Using
isto compare values when==was intended, or vice versa —ischecks identity,==checks value equality.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form