Why Default Mutable List Argument [] Persists Across Calls

⚡ Direct Answer & Key Takeaway

Python evaluates default parameter expressions once when the def statement is executed, not each time the function is called. When you write def add_item(val, items=[]):, a single empty list object is created at definition time and stored in the function's __defaults__ tuple. Every call that omits items reuses and mutates that exact same list object, causing elements from previous calls to persist. Use items=None as the default and initialize items = [] inside the function body.

1. Definition-Time Evaluation and __defaults__ Storage

Most programmers assume that default values in a Python function header are freshly constructed on every call. In reality, def is an executable statement that compiles the function body, creates a function object, and evaluates each default argument expression exactly once during module load or block entry. Those evaluated objects are saved permanently inside the function object's __defaults__ attribute. If the default is an immutable object like 0, True, or 'Guest', rebinding inside the function never damages future calls because the stored value cannot be changed in place. When the default is a mutable object such as [] or {}, Python creates just one list or dictionary object and attaches it to __defaults__. Consequently, every subsequent call that omits that optional argument receives a direct reference to the same memory address, accumulating changes across completely unrelated function invocations.

  • def evaluates default expressions once at function creation time, not per call.
  • The single default list object lives inside func.__defaults__ for the program's lifetime.
  • Immutable defaults (int, str, None, tuple) are safe because they cannot be mutated in place.

2. Tracing Repeated Calls When an Explicit List Is Mixed In

CBSE output-tracing problems love mixing default calls with explicit list arguments to test whether you track which list object is mutated at each step. Suppose def push_log(msg, log=[]): appends msg and returns log. On call one, push_log('A') omits log, so Python binds log to the shared default list, appending 'A' and returning ['A']. On call two, push_log('B', []) supplies a brand-new caller list; this call modifies only that temporary list, returning ['B'] without touching __defaults__. On call three, push_log('C') omits log again, so Python falls back to the stored default list—which still holds ['A']—and appends 'C' to produce ['A', 'C']. Even worse, if a caller captures r1 = push_log('A') and r2 = push_log('C'), both r1 and r2 point to the identical list object, so r1 == r2 == ['A', 'C']!

  • Passing an explicit list isolates that call while preserving existing items in __defaults__.
  • Omitted calls share the exact same list reference (r1 is r2 evaluates to True).
  • Mutating the returned list outside the function also alters future default calls.

3. The None Sentinel Pattern and Safe Alternatives

The standard Python fix for mutable default arguments is the None sentinel pattern: set items=None in the function signature, then write if items is None: items = [] as the first executable check inside the function body. Because None is an immutable singleton, __defaults__ stays clean forever, and items = [] runs fresh at call time whenever the caller omits the second argument. Notice the precision of using is None rather than if not items:: if a caller intentionally passes an empty list my_list = [] to collect results in place, if not items: would mistakenly discard my_list and replace it with a detached list, breaking the caller's reference. Always checking if items is None: preserves explicit empty-list arguments while guaranteeing clean isolation for omitted defaults—a crucial distinction in Class 12 projects and viva exams.

  • Use def fn(items=None): followed by if items is None: items = [].
  • Prefer 'is None' over 'not items' so explicit empty lists [] remain linked to the caller.
  • Apply the exact same sentinel pattern for optional dict or set parameters.

4. Mutable Default List Persistence vs None Sentinel Fix

def buggy_cart(item, basket=[]):
    basket.append(item)
    return basket

def safe_cart(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print("Buggy 1:", buggy_cart("Pen"))
print("Buggy explicit:", buggy_cart("Scale", ["Eraser"]))
print("Buggy 2:", buggy_cart("Book"))
print("Stored default:", buggy_cart.__defaults__)

print("Safe 1:", safe_cart("Pen"))
print("Safe 2:", safe_cart("Book"))

Verified Console / Dry-Run Output:

Buggy 1: ['Pen']
Buggy explicit: ['Eraser', 'Scale']
Buggy 2: ['Pen', 'Book']
Stored default: (['Pen', 'Book'],)
Safe 1: ['Pen']
Safe 2: ['Book']

5. Call-by-Call Trace of Shared Default List vs None Sentinel

Call Sequence (def f(x, a=[]))List Object UsedReturned ValueState of f.__defaults__
f(10)Shared default list[10]([10],)
f(20, [5])Explicit caller list [5][5, 20]([10],) (unchanged)
f(30)Shared default list[10, 30]([10, 30],)
safe_f(10) with a=NoneFresh list created inside body[10](None,) (clean)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Python Function Pitfalls in a Free 1:1 Practice Pod

Debug subtle Python default-argument traps with 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 practice session to master CBSE 083 output prediction and clean coding patterns.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Assuming Python creates a brand-new empty list [] every time the function is invoked.
  • Avoid Mistake: Using if not basket: instead of if basket is None:, which breaks callers passing an explicit empty list [].
  • Avoid Mistake: Forgetting that the exact same persistence bug happens with mutable dictionaries ({}) and sets (set()).
  • Avoid Mistake: Missing that an explicit call like buggy_cart('Scale', ['Eraser']) leaves the stored default list untouched for later default calls.
  • Examiner / Mentor Tip: In viva, explain that 'def evaluates default arguments once at definition time'—that single sentence earns full conceptual credit.
  • Examiner / Mentor Tip: When tracing def f(a=[]): in output questions, maintain one persistent box for the default list across all calls omitting that argument.
  • Examiner / Mentor Tip: Always use the items=None sentinel pattern in your own CBSE practical file programs.

7. Interactive Concept Check Quiz

Question: What is printed by the final line?\ndef add(val, L=[]):\n L.append(val)\n return L\nadd(1)\nadd(2, [10])\nprint(add(3))

8. Frequently Asked Questions

Does the same persistence bug happen with a default dictionary {} or set?
Yes. Dictionaries ({}), sets (set()), and custom mutable objects all get created once when def runs and stored in __defaults__, so mutating them persists across calls.
Why does items=None solve the problem when [] fails?
No, because None is an immutable singleton. Checking if items is None: inside the function runs items = [] dynamically at call time, giving each default call its own fresh list.
Why is if items is None: better than if not items:?
If a caller passes an empty list my_list = [] intending for the function to append into my_list, if not items: evaluates to True and replaces items with a brand-new list, leaving my_list empty. Using is None avoids this bug.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class