The mutable default argument trap occurs when you use a mutable object like a list
[], a dictionary{}, or a set as a default parameter in a function definition.In Python, default arguments are evaluated exactly once when the function is first defined, not every time the function is called. This means that if you modify that mutable default argument inside the function, you are changing a single, shared object that persists across every subsequent call to that function.
def append_to_list(element, target_list=[]): # The trap is set here
target_list.append(element)
return target_list
# First call works as expected
print(append_to_list("apple"))
# Output: ['apple']
# Second call targets a brand new item... or does it?
print(append_to_list("banana"))
# Output: ['apple', 'banana'] -> Uh oh! 'apple' is still there.
# Third call continues to pollute the same list
print(append_to_list("cherry"))
# Output: ['apple', 'banana', 'cherry']
# How to Fix It: The Idiomatic Python Solution
# To avoid this trap, use None as the default placeholder value. None is immutable, making it completely safe. Then, check for None inside the function body and instantiate a fresh, brand-new mutable object on the spot.
def append_to_list(element, target_list = None): # Safe immutable placeholder
if target_list is None:
target_list = [] # A brand-new list is created every single execution
target_list.append(element)
return target_list
print(append_to_list("apple")) # Output: ['apple']
print(append_to_list("banana")) # Output: ['banana']
print(append_to_list("cherry")) # Output: ['cherry']