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

Varnan K
  • 1,237
  • 8
  • 16

1 Answers1

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
sshashank124
  • 31,495
  • 9
  • 67
  • 76