Consider this example
def dump(value):
print value
items = []
for i in range(0, 2):
items.append(lambda: dump(i))
for item in items:
item()
output:
1
1
how can i get:
0
1
You can use a parameter with a default value on the lambda:
for i in range(0, 2):
items.append(lambda i=i: dump(i))
This works because the default value is evaluated when the function is defined, not when it is called.
You can use:
for i in range(0, 2):
items.append(lambda i=i: dump(i))
to capture the current value of i
This works because default parameter values are evaluated at function creation time, and i
is not the external variable, but a function parameter that will have the value you want as default.
A more detailed explanation can be found in this answer.
For completeness, you can also do:
for i in range(0, 2):
items.append((lambda i: lambda: dump(i))(i))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With