What is the mutable default argument pitfall in Python?
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.
Previous
What is Python's comprehension advanced patterns?
Next
What is the walrus operator (:=) in Python?