How to return a list of lambda function?
How to create a list of different lambda functions.
python - How do I create a list of lambdas (in a list comprehension/for loop)? - Stack Overflow
Lambda function
Hi! Just a simple question, I was wondering how to create a list of different lambda functions like so:
[(lambda x: x*i) for i in range(3)]
Ideally, this should return an output like this:
[lambda x: x*0, lambda x: x*1, lambda x: x*2]
However, the actual output is like so:
[lambda x: x*2, lambda x: x*2, lambda x: x*2]
How would I go about producing the desired output? Thanks!
You have:
listOfLambdas = [lambda: i*i for i in range(6)]
for f in listOfLambdas:
print f()
Output:
25
25
25
25
25
25
You need currying! Aside from being delicious, use this default value "hack".
listOfLambdas = [lambda i=i: i*i for i in range(6)]
for f in listOfLambdas:
print f()
Output:
0
1
4
9
16
25
Note the i=i. That's where the magic happens.
I'm guessing that the lambda you're creating in the list comprehension is bound to the variable i which eventually ends up at 5. Thus, when you evaluate the lambdas after the fact, they're all bound to 5 and end up calculating 25. The same thing is happening with num in your second example. When you evaluate the lambda inside the loop it's num hasn't changed so you get the right value. After the loop, num is 5...
I'm not quite sure what you're going for, so I'm not sure how to suggest a solution. How about this?
def square(x): return lambda : x*x
listOfLambdas = [square(i) for i in [1,2,3,4,5]]
for f in listOfLambdas: print f()
This gives me the expected output:
1
4
9
16
25
Another way to think of this is that a lambda "captures" its lexical environment at the point where it is created. So, if you give it num it doesn't actually resolve that value until its invoked. This is both confusing and powerful.