Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python lambda comprehension print i

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading