Look at this:
functions = []
for i in range(3):
functions.append(lambda: i)
for f in functions:
print(f())
What would you expect?
0
1
2
Actual output:
2
2
2
Why? The lambdas don't store the current value of
i. They remember the variable i.By the time the functions are called, the loop has finished and
i is 2.This is called late binding.
If you actually want each function to capture the current value:
functions = []
for i in range(3):
functions.append(lambda i=i: i)
Now:
0
1
2
This becomes particularly important when creating callbacks inside loops, especially in GUI code, asynchronous code, and event-driven applications.
The bug isn't in
lambda. It's in understanding when the variable is looked up.