Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda with different expression returns same output [duplicate]

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?

like image 978
Avi Shah Avatar asked Sep 06 '26 12:09

Avi Shah


1 Answers

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.

like image 62
sarartur Avatar answered Sep 08 '26 02:09

sarartur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!