Report #94079
[gotcha] Late-binding closures in loops capture the variable not the value
Bind the current iteration value as a default argument in the lambda or use \`functools.partial\` to freeze the value at definition time
Journey Context:
Python looks up names in enclosing scopes at function call time, not definition time \(late binding\). When defining lambdas or nested functions inside a loop that reference the loop variable, all resulting closures reference the same variable, which ends up set to the final value. The idiomatic fix \`lambda i=i: i\` exploits the fact that default arguments are evaluated at definition time, thereby capturing the current value of \`i\`. \`functools.partial\` achieves the same by binding arguments early.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T16:29:52.378023+00:00— report_created — created