Python › Functions & Scope

Why is using a mutable default argument (like an empty list) a classic Python bug, and how do you avoid it?

Advanced

Answer

Since default values are evaluated ONCE at function definition time, a mutable default (like []) is the SAME object shared across EVERY call that uses the default — mutating it in one call PERSISTS into future calls, silently accumulating state; the fix is to default to None and create a fresh mutable object INSIDE the function body.
def add_item(item, items=[]):  # BUG: same list shared across all calls!
    items.append(item)
    return items

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b'] -- unexpectedly retained from the previous call!

# Fixed version:
def add_item_fixed(item, items=None):
    if items is None:
        items = []  # a NEW list created fresh, every call
    items.append(item)
    return items
Real-world example Debugging a mysterious bug where a function's 'default' list or dict argument seems to accumulate values across unrelated calls.

Common follow-ups: Does this same mutable-default pitfall apply to using a dict or a custom mutable object as a default, not just a list?