Report #97224
[gotcha] Lambdas or nested functions in a loop all close over the same loop variable
Bind the current value as a default argument, e.g. \`lambda x=i: ...\` or \`functools.partial\(fn, i\)\`, so each closure captures the value at iteration time rather than the variable name.
Journey Context:
Python's closures capture variables by reference, not by value. In a loop, all the closures created see the same name \`i\`, and by the time they run the loop has finished and \`i\` holds the final value. Using a default argument is the idiomatic fix because default values are evaluated at definition time, freezing the current loop value into each closure. \`functools.partial\` is equivalent and reads better for non-lambdas. Many developers first try list-comprehension tricks or reassigning \`i\` inside the loop, but those still leave every closure pointing at the same variable; the binding must happen in the closure's own scope.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T04:45:37.813938+00:00— report_created — created