Python default keyword parameters persisting

Viewed 29

Consider the following code

def func(para = []):
    para.append(1)
    return para
    
print(func())
print(func())

the output is

[1]
[1, 1]

The function somehow reuses para, I realize pointers are used for classes, lists, dicts, etc but here the para should be redefined as it is not being passed when func is called.

I don't remember it being like this, either way, is there a way to make it so para resets to a empty list when func is executed?

1 Answers

The reason that it's happening is because a list is mutable, to fix it use a immutable value like a string as a default parameter.

Related