How do I create a list of lambdas (in a list comprehension/for loop)?

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.

Leave a Comment