r/CodingForBeginners • u/ClickOk5811 • 18h 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?
3
u/Dashing_McHandsome 17h ago
I've spent my career doing mostly Java and when I come in to contact with python this is the kind of stuff I see and it makes me nuts. Your proposed solution to this problem is to obscure the type of basket, so I can't tell what is happening when I call this function unless I go read it. Is that really the solution in this language? That seems so unacceptable to me.
2
u/stepback269 17h ago
It's not a bug. When you *return* basket with the first running of the subroutine, basket gets added to the namespace of the outer scope calling the subroutine.
The when you run / call the subroutine the second time, basket is already defined in that outer scope and the subroutine does not need to use the default empty value.
Nice reminder though. Thanks !
1
u/JoeStrout 16h ago
MiniScript avoids this gotcha by "freezing" (rendering immutable) any lists or maps that are used as default arguments. So if you try to mutate the list or map (e.g. by appending an item to it), you get an error; but you can still read them just fine.
Learn more at: https://miniscript.org
1
u/Beginning-Seat5221 14h ago
Functional Programmers hate this one trick.
1
u/igotshadowbaned 13h ago
...The actual solution is to not create basket as if it were an unpassed argument and instead just declare it in the function
1
u/justaguyonthebus 13h ago
Can we not fix this already? Who would intentionally use it that way?
1
u/masterofaiml 13h ago
It’s not a bug 🥲
Try www.pythonmastery.io, it’s a free resource for learning and practicing python.
1
u/Economy_Bedroom3902 12h ago
def add_item(item, basket=[]):This is quite poor software design. A function which modifies an existing list should not have have a default behavior of creating a new list if a list to modify is not present. This is an example of coupling, where you are asking the same code to perform multiple unrelated functions. Have separate functions for creating a new list vs modifying an existing list.
1
u/Equal-Combination752 7h ago
Why does basket=None change it to None, but basket=[] doesn’t change it to []?
1
u/Amilektrevitrioelis 5h ago
Not a bug.
https://docs.python.org/3/tutorial/controlflow.html#default-argument-values