0

I'm a beginner in Python. If you run the following simple code:

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

The output is:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

The third output doesn't make sense to me. I found an explanation here, but again not clear. I mean if the list stores the previous value in memory [0, 1], why then not store [3, 2, 1, 0, 1, 4]? According to the explanation mentioned above, the function "uses the original list stored in the original memory block". But we have two [0, 1], and [3, 2, 1, 0, 1, 4].

How can I say which one is the original?

AhmedWas
  • 1,205
  • 3
  • 23
  • 38
  • 1
    https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument?s=1|784.4155 – Jean-François Fabre Nov 01 '17 at 07:19
  • 1
    on the second call you're not using the default argument, so it's only stored in call 1 and 3. – Jean-François Fabre Nov 01 '17 at 07:24
  • @Jean-FrançoisFabre thanks for the comment. But can I overcome this thing? I mean if I want to call such function without using the previous value. I read that one may use None, I tried it but it didn't work. – AhmedWas Nov 01 '17 at 07:53
  • it means use None as default argument, and if it's None, create a list in the function so it's independent from other calls. never use a mutable default value. – Jean-François Fabre Nov 01 '17 at 07:55

0 Answers0