Consider the following Python code snippet:
fns = []
for i in range(2):
x = i
fns.append(lambda: x)
for fn in fns:
print(fn())
Why does this print
1
1
instead of
0
1
Consider the following Python code snippet:
fns = []
for i in range(2):
x = i
fns.append(lambda: x)
for fn in fns:
print(fn())
Why does this print
1
1
instead of
0
1
The lambda function is printing the value of the variable x
:
fns = []
for i in range(2):
x = i
fns.append(lambda: x)
x = 4
for fn in fns:
print(fn())
#4
#4