Home > database >  Python default keyword parameters persisting
Python default keyword parameters persisting

Time:08-07

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?

CodePudding user response:

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.

CodePudding user response:

def func(para = []):
    return [*para, 1]
    
print(func())
print(func())

prints

[1]
[1]
  • Related