FeroxCloudJoin free
5

Why does my Python default list argument keep growing?

SRAsked by Sofia Rossi · 16d
python
def add(x, items=[]):
    items.append(x)
    return items

Calling it twice gives me both values!

#python

1 answer

4

Accepted answer

Default arguments are evaluated once, at definition time. Use None:

python
def add(x, items=None):
    items = [] if items is None else items
    items.append(x)
    return items

print(add(1)); print(add(2))
PRAnswered by Priya Raman · 16dMentor

Sign in to answer.