download

Why does a default list keep items from earlier calls?

Python~8 minReviewed 3 Dec 2026Free · No sign-in

Question

A helper records events in a list. Callers often omit bucket to start fresh, expecting a one-item list each time. Instead, two separate calls end up sharing the same list.

  1. Predict the three lines the starter prints and explain why first and second share one list.
  2. Fix add_event so omitting bucket creates a new list each call, while passing an explicit empty list shared = [] still appends into shared.
"CODE · PYTHON"
def add_event(name, bucket=[]):
    bucket.append(name)
    return bucket


first = add_event("login")
second = add_event("logout")
print(first)
print(second)
print(first is second)
Show hints (3)
  1. "WHEN DEFAULTS RUN"

    Python evaluates bucket=[] only once, when def add_event runs, not on each call. Check add_event.__defaults__.

  2. "USE A SENTINEL"

    Set the default to None and create a fresh list inside the function body whenever bucket is omitted.

  3. "EMPTY LIST CHECK"

    Test if bucket is None: rather than bucket = bucket or []. An explicit empty list [] is falsy.

Show checked explanation

The starter prints ['login', 'logout'], ['login', 'logout'], and True. Python evaluates bucket=[] once at def time and stores that single list in add_event.__defaults__. Fix it by defaulting to None and assigning bucket = [] only when bucket is None.

"SOLUTION · PYTHON"
def add_event(name, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(name)
    return bucket


first = add_event("login")
second = add_event("logout")
shared = []
third = add_event("ping", shared)

print(first)
print(second)
print(first is second)
print(shared, third is shared)
"OUTPUT"
['login']
['logout']
False
['ping'] True

Code run on CPython 3.12.10 against the starter bug, fixed solution, and dataclass edge cases above. Checked by an editor other than the author.

Walkthrough

In Python, def is an executable statement. When it runs, Python evaluates every default expression once and saves the resulting tuple on add_event.__defaults__. Each call that omits bucket reuses that exact list object.

Stepadd_event.__defaults__firstsecond
def add_event([],)not setnot set
first = add_event("login")(['login'],)['login']not set
second = add_event("logout")(['login', 'logout'],)['login', 'logout']['login', 'logout']

Because first and second point to the same list in __defaults__, first is second is True. Even first changes when the second call runs.

Setting bucket=None fixes the bug because None is immutable. Inside the body, if bucket is None: runs on every call and builds a fresh list only when the caller omitted bucket.

Do not write bucket = bucket or []. An empty list [] is falsy in Python. Passing shared = [] would skip shared, build a brand-new list, and leave shared empty. Checking is None keeps the caller's list intact.

For classes using dataclasses, Python blocks events: list[str] = [] with a ValueError. Use field(default_factory=list) so each instance gets its own list:

"PYTHON"
from dataclasses import dataclass, field


@dataclass
class AuditLog:
    events: list[str] = field(default_factory=list)

This bug also differs from shallow copying and closure late binding. Nobody copied a dict here, and closures read variables late when called. Default arguments evaluate early, at def time.

Common mistakes

  • Writing bucket = bucket or []. Because [] is falsy, passing an empty caller list shared = [] silently creates a new list and leaves shared unchanged.
  • Using datetime.now() or uuid.uuid4() as a default value. Python calls it once at import time, so every later call gets the same startup timestamp or ID.
  • Putting events = [] directly on a plain class body instead of self.events = [] in __init__. Every instance then appends to one shared class list.
  • Blaming shallow copying. Shallow copying shares nested objects between two containers, whereas here Python created only one list in __defaults__ before any call ran.

Follow-up questions

  • "What if None is a valid value that a caller might pass on purpose?" Define a private sentinel object at module level: _MISSING = object(). Set def record(value=_MISSING): and check if value is _MISSING:. No caller can pass _MISSING by accident, so record(None) preserves None while record() builds the fresh default.
  • "How does this compare to closure late binding in a loop?" They happen at opposite times. A closure reads its outer loop variable late, when the function is called, so every callback sees the final loop value. A default argument runs early, once at def time. Early evaluation helps freeze an integer in lambda i=i: i, but shares a mutable list across calls.
  • "Is a mutable default argument ever a good idea?" Rarely, except for a tiny private cache such as _cache={} inside a helper. In production code, prefer functools.lru_cache or an explicit cache object. Hidden state inside __defaults__ leaks across unit tests and appears in help() and inspect.signature().

What a strong answer covers

Explains that defaults evaluate once at def time and live in __defaults__. Fixes it with None and is None, warns why bucket or [] breaks explicit empty lists, and names field(default_factory=list) for dataclasses.

Open in interactive practice deck →

Original OfferVibe question. Python Function Definitions · Python FAQ: Shared Defaults · Python dataclasses Mutable Default Values.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.