Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Append lambda functions to list [duplicate]

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??

like image 897
ywat Avatar asked Dec 12 '13 06:12

ywat


People also ask

Can lambda functions be used to iterate through a list?

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 lambda function in Python?

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.

Can we return multiple values from a lambda function?

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).

Is lambda faster than list comprehension?

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.


1 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
like image 126
thefourtheye Avatar answered Sep 29 '22 21:09

thefourtheye