Report #16534
[gotcha] Lambda or nested function in loop captures variable by reference yielding final value for all iterations
Bind the loop variable as a default argument at definition time to capture the current value: \`lambda x, i=i: ...\` or use \`functools.partial\`
Journey Context:
Python closures look up names in enclosing scopes at runtime when the function is called, not at definition time when the loop variable is bound. Since the loop variable is rebound on each iteration, all closures in the list share a reference to the same name, which resolves to the final value after the loop completes. Using a default argument captures the current iteration's value because default arguments are evaluated at definition time, creating independent bindings for each closure.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T02:53:12.077626+00:00— report_created — created