flist = []
for i in range(3):
flist.append(lambda: i)
for f in flist:
print f()
I don't know why its returning 2,2,2
flist = []
for i in range(3):
flist.append(lambda: i)
for f in flist:
print f()
I don't know why its returning 2,2,2
In the last iteration through the first loop, your i
value is 2 and hence ALL the i
values in each element of the list are now 2. This is because you have created a live reference to the i
variable.
Here is a simplified demonstration:
a = 5
c = lambda: a
a += 5
>>> c()
10