-1

Check out the following code:

def f(x, myList = []):
    myList.append(x)
    return myList

f(6)

returns [6]

while

f(7)

returns [6, 7]

My question is why it doesn't use the default myList value when no value is specified.

On the other hand, this code works fine

def f(x, myList = None):
if myList == None:
    # This WILL allocate a new list on every call to the function.
    myList = []
myList.append(x)
return myList

f(6)

returns [6]

f(7)

returns [7]

Why in the later case it takes the default argument value but not in the former case?

Lokesh
  • 2,842
  • 7
  • 32
  • 47

1 Answers1

0

The default argument is init at the point of defining the function. So for mutable type values, the function calls share the same variable. You can refer Why are default values shared between objects.

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43