1

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?

Kryptic Coconut
  • 159
  • 1
  • 10
  • Lists are mutable, so if you alter it the changes will stick. Some IDEs will even give you a warning. What are you trying to do? – Guy Aug 07 '22 at 04:32
  • Try: def func(para = None): if para is None: para = [] para.append(1) return para print(func()) print(func()) – copper.hat Aug 07 '22 at 06:00

1 Answers1

-1

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.