2

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I recently met a problem in Python. Code:

 def f(a, L=[]):
   L.append(a)
   return L

 print f(1)
 print f(2)
 print f(3)

the output would be

[1]
[1, 2]
[1, 2, 3]

but why the value in the local list: L in the function f remains unchanged? Because L is a local variable, I think the output should be:

[1]
[2]
[3]

I tried another way to implement this function: Code:

def f(a, L=None):
  if L is None:
  L = []
  L.append(a)
  return L 

This time, the output is:

[1]
[2]
[3]

I just don't understand why... Does anyone have some ideas? many thanks.

Community
  • 1
  • 1
Rain
  • 117
  • 2
  • 9

2 Answers2

5

The default parameters are in fact initialized when the function is defined, so

def f(L = []): pass

is quite similar to

global default_L = []
def f(L = default_L): pass

You can see this way that it is the same list object that is used in every invocation of the function.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
  • this is a very very useful piece of information. just saved me a bulky psychiatry bill. Yet, it is a very weird choice on python's part. I don't know if it's just me but this is horribly unintuitive. – toraman Oct 11 '22 at 07:19
3

The list in def f(a, L=[]) is defined as the function is defined. It is the same list every time you call the function without a keyword argument.

Setting the keyword to None and checking / creating as you have done is the usual work around for this sort of behaviour.

MattH
  • 37,273
  • 11
  • 82
  • 84