I wrote this simple code:
def makelist():
L = []
for i in range(5):
L.append(lambda x: i**x)
return L
ok, now I call
mylist = makelist()
because the enclosing scope variable is looked up when the nested functions are later called, they all effectively remember the same value: because of this, I expected to find the value the loop variable had on the last loop iteration, but when I check my list I see:
>>> mylist[0](0)
1
>>> mylist[0](1)
4
>>> mylist[0](2)
16
>>>
I'm so confused, why my code doesn't retain the last for loop values? Why I don't have to explicitly retain enclosing scope values with default arguments like this:
L.append(lambda x, i=i: i ** x)
Thanks in advance