0

I saw this blog post showing an interesting Python memory block behavior. I read through the explanation but still not sure.

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

f(2)
f(3) 

Prints

[0, 1]
[0, 1, 0, 1, 4]

Why not these below? After finishing f(2) where does l get cached? I thought all the local variables would get wiped out.

[0, 1]
[0, 1, 4]
E.K.
  • 4,179
  • 8
  • 30
  • 50

1 Answers1

1

All local variables do get wiped out, but the default value for l is not local to the function body but actually part of the function definition, initialized once when the function object is constructed.

So here, l serves as a "cache" of sorts, exploiting the mutability of lists.

jedwards
  • 29,432
  • 3
  • 65
  • 92