Take this code snippet for example:
a = []
for x in range(2):
a.append(lambda: print(x))
print(a[0](), a[1]())
The output is:
1 1
But I expected it to be
0 1
How do I fix this?
Use default arguments:
a = []
for x in range(2):
a.append(lambda x = x: print(x))
print(a[0](), a[1]())
This works because the default value is evaluated when the function is created. Otherwise all lambda functions will point to the last value of x, which was 1.
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