In Python, using mutable objects (like lists or dictionaries) as default argument values can lead to unexpected behavior. This happens because the default value is created once when the function is defined — not each time it’s called.
The Problem
Here’s an example of what not to do:
def append_to_list(val, lst=[]): # Bad!
lst.append(val)
return lst
print(append_to_list(1)) # [1]
print(append_to_list(2)) # [1, 2] - oops, shared list!
Because lst
is defined once, all calls share the same list — which is usually not what you want.
The Right Way
Use None
as the default, then create a new list inside the function if needed:
def append_to_list(val, lst=None): # Good!
if lst is None:
lst = []
lst.append(val)
return lst
print(append_to_list(1)) # [1]
print(append_to_list(2)) # [2] - separate list each time
Key Takeaways
- Default argument values are evaluated once, at function definition time.
- Using mutable defaults can cause data to be shared between calls.
- Instead, use
None
and create a new object inside the function.
Remember: Immutable defaults are safe (like numbers, strings, or tuples), but mutable defaults can be a subtle source of bugs.
0 Comments