-1

sorry i really do not know how to describe this issue accurately in the title

I define a function like this

def f(v,l=[]):
    l.append(v)
    return l

In my understanding, the output should be like this:

the first call should return [0]

the second call should return [1]

the third call should return [2]

But.. here is the real output

>>> f(0)
[0]
>>> f(1)
[0, 1]
>>> f(2)
[0, 1, 2]
Kramer Li
  • 2,284
  • 5
  • 27
  • 55
  • 3
    don't use `l=[]` because Python creates this `[]` only once when script is loaded. – furas Nov 14 '16 at 05:32
  • 1
    To be more precise, default arguments are evaluated when the function definition is executed, not when the function is called. – PM 2Ring Nov 14 '16 at 05:42

1 Answers1

4

You have to do

def f(v, l=None):
    if l is None:
        l = []
    l.append(v)
    return l

because in l=[] this list [] is created only once when script is loaded.

More precise (as @PM2Ring said) it is created when the function definition is executed, not when the function is called.

See: http://docs.python-guide.org/en/latest/writing/gotchas/

furas
  • 134,197
  • 12
  • 106
  • 148