Fix Late Binding Closures in Python Loops
Why lambdas inside a Python loop all return the final loop value, and how lambda i=i: i captures each iteration.
By the end of this tutorial you will know:
- Why closures in Python look up loop variables when called, not when created
- How to capture the current iteration value with a default parameter (
i=i) - How
functools.partialoffers an explicit alternative
Prerequisites: Python 3 installed.
1. The big idea
When you create a lambda or inner def inside a for loop, Python does not snapshot the current value of i. Instead, the function remembers the variable name i in the surrounding scope. By the time you actually call the functions after the loop finishes, i is stuck on its final value.
2. Reproducing the bug
callbacks = []
for i in range(4):
callbacks.append(lambda: i)
print([fn() for fn in callbacks])[3, 3, 3, 3]Every callback returned 3 instead of [0, 1, 2, 3]!
3. The fix: bind i=i as a default argument
Because Python evaluates default argument values at function definition time, adding i=i snapshots the current value of i for each iteration.
callbacks = []
for i in range(4):
callbacks.append(lambda i=i: i)
print([fn() for fn in callbacks])[0, 1, 2, 3]You can also use functools.partial:
from functools import partial
def make_val(x):
return x
callbacks = [partial(make_val, i) for i in range(4)]Run python3 fixed.py and confirm it prints [0, 1, 2, 3].
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
lambda: handle(item) inside a for loop | All handlers act on the last item | Write lambda item=item: handle(item) |
5. What you learned
You now know how Python late-binding closures work and how default parameters or functools.partial capture loop values immediately.