r/CodingForBeginners • u/ClickOk5811 • 56m ago
A Python bug that confuses almost everyone at first: the list that remembers things
If you've seen this, you're not alone. Here's a small function. Before reading on, guess what the two lines print.
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("bread"))Many people expect:
['apple']
['bread']But Python 3.13 prints:
['apple']
['apple', 'bread']Why it happens: the default value [] is created once, when the function is defined, not each time it's called. Every call that doesn't pass basket reuses that same list. You can even see it:
print(add_item.__defaults__) # (['apple', 'bread'],)The usual fix: use None as the default and create the list inside the function.
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("apple")) # ['apple']
print(add_item("bread")) # ['bread']Now each call gets its own new list.
A rule of thumb: don't use a list, dict or set as a default value. Numbers, strings and None are fine, because they can't be changed in place.
If anything is unclear, ask below. I'm happy to explain more. Also curious: did you guess right before running it?
