Report #103475
[gotcha] Lambda or nested function defined inside a loop closes over the loop variable, not its value
Bind the value at definition time with a default argument, e.g. lambda i=i: i or def make\_cb\(i=i\): return lambda: i. In comprehensions, freeze iteration values the same way rather than depending on the loop variable after the loop.
Journey Context:
Nested functions and lambdas capture variables by reference, not by value. In a for loop, every created closure shares the same variable name, so after the loop they all see the final value. The classic fix exploits the fact that default arguments are evaluated at definition time: lambda x=i: x creates a closure whose default captures the current loop value. The same trap appears inside comprehensions, where closures still see the iteration variable. This is intended late-binding semantics, not a bug, but it is one of the most common silent failures in real code.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-11T04:27:29.089854+00:00— report_created — created