1

The problem is simple, but I couldn't find the solution to it after searching for a while, so here goes my question:

How do I pass the value of a variable into a lambda function instead of the references to it?

To give you an example:

my_lambdas = []

for i in range(5):
    my_lambdas.append(lambda: print(i))

for l in my_lambdas:
    l()

Running the above code results in 5 printed '4's. I'm guessing this happens because the lambdas are being run after variable i is set to 4.

I would like it to print 0 to 4. How can I achieve this?

Edit: I need a solution using lambdas and iteration.

martineau
  • 112,593
  • 23
  • 157
  • 280
Syphon
  • 179
  • 10

0 Answers0