1

I was really surprised by the following Python code

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l) 

f(2) #[0, 1]
f(3) #[0, 1, 0, 1, 4]

The question is why Python uses the same l list, when in function definition is always defined as l=[]

com
  • 2,606
  • 6
  • 29
  • 44
  • 5
    This is a frequently-asked dup; give me a sec to find the canonical answer. It's also explained in the Python FAQ. – abarnert Mar 13 '18 at 03:08
  • 3
    [Here ya go](http://docs.python-guide.org/en/latest/writing/gotchas/) – eqwert Mar 13 '18 at 03:10
  • @eqwert, thank you for the link. But this is really confusing, I wonder why they decided to do it this way – com Mar 13 '18 at 04:40

2 Answers2

1

A default value is bound at function definition time. This is a common "gotcha" when assigning dictionaries or lists as defaults.

For some additional detail, see this blog post, which has a section on mutable default values.

You can think of it as creating the object and binding it to the formal parameter name when the python interpreter first sees the function definition. From that point forward, when the function is invoked, that same mutable object is provided to the function if no user-supplied value is present.

It is certainly a surprise at first, but fits into the way python does things.

1

Because it creates one empty list at function definition and sets a reference to that object as default argument. This default reference always points to that same object.

Julien
  • 13,986
  • 5
  • 29
  • 53