python
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
print(add_item(3))
Answer:
[1]
[1, 2]
[1, 2, 3]
Surprised? Mutable default arguments in Python are created once, when the function is defined - not each time it's called. So that same list keeps getting reused and mutated across calls.
The fix:
python
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
This exact bug has caused real production incidents. It's also a favorite "gotcha" question at Python-heavy companies.
Did you know about this one, or did it just break your brain a little? 😄