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

1 Upvotes

1 comment sorted by

1

u/Dashing_McHandsome 11m 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.