
This is the most famous “gotcha” in all of Python: the Mutable Default Argument bug. It’s a bug that confuses every developer exactly once.
Look at this simple function:
def add_to_list(item, my_list=[]):
my_list.append(item)
return my_listIt seems simple, right? Let’s use it.
Problem Code:
print(add_to_list(1)) # Output: [1] (Looks good) print(add_to_list(2)) # Output: [1, 2] (Wait, what?!) print(add_to_list(3)) # Output: [1, 2, 3] (What is happening?!)
The list is remembering the items from previous calls!
The Cause: Python Creates Defaults Once
Python creates the default my_list=[] only one time, when the function is first defined. This one single list is then used for every call to that function.
When you append 1, it changes that one list. When you call it again and append 2, it changes the same list.
The Fix: Use None as the Default
The correct, professional pattern is to use None as the default and then create a new list inside the function. this avoids the Mutable Default Argument pitfall.
# The correct, safe way:
def add_to_list(item, my_list=None):
if my_list is None:
my_list = [] # Create a NEW list every time
my_list.append(item)
return my_listTesting the Fix:
print(add_to_list(1)) # Output: [1] print(add_to_list(2)) # Output: [2] print(add_to_list(3)) # Output: [3]
Now it works as expected, because each call gets its own fresh, empty list.
Key Takeaways
- The Mutable Default Argument bug confuses many developers in Python.
- Python creates default arguments only once, leading to unexpected behaviour when lists retain items between function calls.
- To fix this issue, use None as the default and create a new list within the function to ensure fresh instances per call.





