Join waitlist
PythonCommunity question

python default argument list keeps old values??

Asked by aman khan 2 months ago 2 answers 11 votes
def add(x, lst=[]):
    lst.append(x)
    return lst
print(add(1))
print(add(2))

I thought it prints [1] and [2]. it prints [1] and [1, 2]. why is the list shared between calls

2 answers

Neha Joshi2 months agoMost voted9

Default values are evaluated once, when the def line runs, not every time you call the function. So both calls get the same list object.

Usual fix:

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

Very common interview question btw

Pranav Bhat2 months ago2

people sometimes use this on purpose as a cache (dict as default) but yeah mostly its a bug

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.