Python: Append lambda functions to list
Question:
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??
Answers:
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
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??
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