8

Can anyone do sanity check?

I'm trying to make functions in for-loop. The point I can't understand is summarized in the following code:

f_list = []
for i in range(10):
    f = lambda j : i
    f_list.append(f)

Then,

>>> f_list[0](0)
9                  #I hope this is 0.
>>> f_list[1](0)
9                  #I hope this is 1.

Why is this happen??

ywat
  • 2,757
  • 5
  • 24
  • 32
  • Thank you for pointing out the past question/answers. Yes, this is actually a duplicate of them. – ywat Dec 12 '13 at 06:32

1 Answers1

10

Edit: Almost the same problem is already discussed in Stackoverflow, here.

This is because of the closure property of python. To get what you actually need, you need to do like this

f = lambda j, i = i : i

So, the output of this program becomes like this

f_list = []
for i in range(5):
    f = lambda j, i = i : i
    f_list.append(f)

for i in range(5):    
    print f_list[i](0)

Output

0
1
2
3
4
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497