Why is a mutable default argument (like def f(x, items=[])) dangerous?
⚡ Short Answer
Default argument values are evaluated once when the function is defined, not on each call. So a mutable default like `items=[]` is shared across all calls — it accumulates data between calls. The fix is `items=None` and create a fresh list inside the function.
☕Coffee Chat Question
Concept Made Simple
“Why is a mutable default argument (like def f(x, items=[])) dangerous?”
🧠Mind Map Answer
Remember It Faster
⌨️Hands-on Keyboard
Learn by Doing
def bad(x, items=[]): # shared default!
items.append(x)
return items
print(bad(1)) # [1]
print(bad(2)) # [1, 2] <- surprise
def good(x, items=None):
items = items or []
items.append(x)
return items
print(good(1)); print(good(2)) # [1] then [1][1] [1, 2] [1] [1]
🔥What If?
Think Beyond the Expected
Why does the second call to `bad(2)` return [1, 2] instead of [2]?
The default list is created once, when `def bad` runs — every call that doesn't pass `items` reuses that same list object, so appends accumulate. Using `items=None` and building a new list inside gives each call its own fresh list.
😂Real World
This is one of the most-asked Python 'gotcha' interview questions and a real source of state-leak bugs in caches, accumulators, and config defaults — the None sentinel pattern is the standard fix.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Using [] or {} as a default value
- ✗Assuming defaults are recreated each call
- ✗Mutating a shared default and blaming the caller
✅Best Practices
- ✓Default to None; build the mutable inside
- ✓Keep defaults immutable
- ✓Document any intentional shared default
🔁Follow-up Questions
- 1Does the same problem apply to dict/set defaults?
- 2When is a mutable default sometimes used deliberately (caching)?
- 3How do keyword-only args help API clarity?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Functions (Python) Interview question: "Why is a mutable default argument (like def f(x, items=[])) dangerous?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.