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??
First off, the Lambda function itself cannot be used to iterate through a list. Lambda, by its very nature, is used to write simple functions without the use of defining them beforehand.
Can we reuse the lambda function? I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers.
That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).
Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With