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
- 2. Tracing Repeated Calls When an Explicit List Is Mixed In
- 3. The None Sentinel Pattern and Safe Alternatives
- 4. Mutable Default List Persistence vs None Sentinel Fix
- 5. Call-by-Call Trace of Shared Default List vs None Sentinel
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
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 Used | Returned Value | State 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=None | Fresh list created inside body | [10] | (None,) (clean) |
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.
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?
Why does items=None solve the problem when [] fails?
Why is if items is None: better than if not items:?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Returning Multiple Values From Python Functions (Tuples)
- Tracing Flow of Execution Across Nested Python Functions (CBSE 083)
- Sorting Lists of Tuples and Dictionaries Using key= in Python
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
