What is the mutable default argument pitfall in Python?
Why Interviewers Ask This
This question targets practical, hands-on experience with Python. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
One of Python's most common gotchas: mutable default arguments are evaluated once when the function is defined, not on each call. def append_to(item, lst=[]): — the same list object is reused across all calls without an explicit argument, causing values to persist between calls. Fix: use None as default and create the mutable object inside the function: def append_to(item, lst=None): if lst is None: lst = []; lst.append(item); return lst. This applies to any mutable type as default: lists, dicts, sets. Immutable defaults (int, str, tuple, None) are safe because they cannot be mutated. This behaviour is intentional and documented but surprises nearly every Python beginner. Use functools.lru_cache with caution for similar reasons with mutable cache keys.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.
Previous
What is Python's comprehension advanced patterns?
Next
What is the walrus operator (:=) in Python?