The following Python program:
d = {}
for x in range(3):
d[x] = lambda: x
print(d[0](), d[1](), d[2]())
outputs:
2 2 2
x
is bound by reference in the lambda
expression. After the for
statement, x
is bound to 2, which explains the output.
I would like x
to be bound by value instead, to get the following output:
0 1 2
How can I achieve this?