0

i came across this question:

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

f(2)
f(3,[3,2,1])
f(3)

Answer given is :

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

explanation: The first function call should be fairly obvious, the loop appends 0 and then 1 to the empty list, l. l is a name for a variable that points to a list stored in memory. The second call starts off by creating a new list in a new block of memory. l then refers to this new list. It then appends 0, 1 and 4 to this new list. So that's great. The third function call is the weird one. It uses the original list stored in the original memory block. That is why it starts off with 0 and 1.

my request: where can i find more info on the why and how of this for a newbie like me. even with the above answer im having trouble understanding the last function call.

thanks in advance for your responses.

Ajay Pai
  • 53
  • 1
  • 6
  • 1
    http://programmers.stackexchange.com/questions/157373/python-mutable-default-argument-why – BlackBear Apr 20 '16 at 13:53
  • any of the posts mentioned in the previous comments will get you there. The difference is that you 2nd call provides the list argument and as suchthe default argument is not used. – rll Apr 20 '16 at 14:04

0 Answers0