Report #56011
[gotcha] Lambda or nested function in loop captures variable, not value \(late binding closure\)
Bind the loop variable as a default argument at definition time: \`lambda x, i=i: x \+ i\` or use \`functools.partial\` to freeze the value
Journey Context:
Python closures look up names in enclosing scopes at runtime, not at definition time. When defining lambdas or inner functions inside a loop, all closures reference the same loop variable. By the time the functions are called, the loop has completed and the variable holds its final value. Binding via a default argument captures the current value of the variable at the moment the function object is created, creating the expected distinct closures.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T00:30:29.833597+00:00— report_created — created