r/CodingForBeginners • • 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?

11 Upvotes

23 comments sorted by

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.

4

u/GlassCommission4916 14h ago

Python is an insane language to people who have used more sensible languages.

1

u/Economy_Bedroom3902 12h ago

I don't think this is particularly ideomatic python.  Python has a typing system, you shouldn't use default empty values to set types for input vars.  A function which both creates new values when executed without the second param and modifies old objects when executed with the param is bad coupling.  Just because it's possible to do this way in python, doesn't make it the "right" way to do it.

1

u/WildCard65 54m ago

It’s because everything is a reference in Python, the only thing copied by value is the reference (PyObject* in CPython)

1

u/KatieKrispy 11h ago

I think you could use a type hint or something like

def add_item(item: str, basket: List[str] | None = None) -> List[str]:
    ...

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/ThreeCharsAtLeast 11h ago

uhm, it's not behaving like that due to the return statement, though.

>>> def add_item(item, basket=[]):
...     basket.append(item)
...     return basket[0]
...
>>> add_item("apple")
'apple'
>>> add_item("bread")
'apple'
>>>

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/Economy_Bedroom3902 12h ago

This function's primary job is to append items to an existing list, not to create new lists.  The creating of new lists is just a bizarre default functionality Op  decided to also give the function to show off the "bug".  Op's described solution is also not much more sane though.

1

u/igotshadowbaned 3h ago

In that case they should just declare the empty list in the function call when applicable instead of the function definition

1

u/justaguyonthebus 13h ago

Can we not fix this already? Who would intentionally use it that way?

1

u/hr_krabbe 3h ago

Only every dynamic programming tutorial ever made.

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/Key_Detail15 6h ago

Having a pointless extra function is also poor design. The function can be safely used like this:

  x = add_item("one", [])    
  x = add_item("two", x)
  y = []
  y = add_item("three", y)

The default is not needed and not useful.

However, this was just a way to illustrate the quirkiness of this default value. You would intuitively expect the original default value to be used each time the function is called with that argument missing.

But the OP hasn't explained why the behaviour is different with None, which is yet another quirk.

Is it because that [] default expression is modified by the function, rather than a copy of it? If so, why doesn't that also happen here:

a = []
a.append("one")
b = []
b.append("two")
print(a, b)          # shows ['one'] ['two']

Appending to 'a' doesn't modify that first '[]', since 'b' gets assigned a fresh one.

1

u/WildCard65 44m ago

Allow me to explain: When Python has to fill in the default values for arguments that have a default value, it reaches into a special dict/list stored in the function itself and grabs the object reference and fills that in for the missing argument.

The reason it behaved “differently” with None instead is because None was specially handled within the function itself and the argument was modified locally to the function itself, but the function still behaved the exact same in both cases.

In your example with append, you are calling the List.append method which was automatically supplied the reference of the variable it was paired with (a and b respectively) while OP’s example is a free standing function.

1

u/Equal-Combination752 7h ago

Why does basket=None change it to None, but basket=[] doesn’t change it to []?

1

u/WildCard65 38m ago

Nothing is changed in either examples, both cases the argument “basket” is given the reference that was stored in the function itself as the default value for the argument.

None is just an immortal singleton object in Python whose reference count is static (neither increases or decreases) and is taught as the universal symbol of “no value present and the statement “basket is None” would be true (is statement checks if both sides is the exact same object where “[] is []” would be false)