Find Mistake: Mutable Default Argument
Find the Mistake Medium
Question
This function behaves unexpectedly across calls. What is wrong?
Code
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1))
print(add_item(2))
Hint
Default arguments are evaluated once, not per call.
Explanation
The default argument [] is created once at function definition time, so the same list is shared across calls. The second call returns [1, 2] instead of [2]. The fix is to use def add_item(item, lst=None): if lst is None: lst = [] to create a fresh list each call.
Related Resources
Related Lessons
- Python Functions
Default argument pitfalls.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.