I'm trying to use comprehensions to write a list of lambdas, where each lambda when called will print the index that is it's position in the list.
list = [lambda : print(i) for i in range(10)]
list[0]()
But the problem is that calling any of the lambdas all produce the same result, they print 9. How can I capture the value of i in the way I intend to for each lambda?
You need to make sure that i
is evaluated and bound inside the body of the lambda at the time the lambda is defined, rather than delaying it until it's called (by which time the loop has finished and i = 9
). One way of doing that is to use i
as the default value of a parameter to the lambda, since the default is evaluated when the function is defined rather than when it's called:
>>> funcs = [lambda x=i: print(x) for i in range(10)]
>>> funcs[0]()
0
>>> funcs[1]()
1
Note that you don't actually need to use a different variable name; you can name the parameter i
and it will be shadowed inside the lambda body and still work the same way:
>>> funcs = [lambda i=i: print(i) for i in range(10)]