Report #102990
[gotcha] Lambdas or nested functions in a loop all close over the same loop variable
Bind the current loop value as a default argument, e.g. \`lambda i=i: ...\` or use \`functools.partial\`.
Journey Context:
Python's late-binding closures look up variable names when the function runs, not when it is defined. In a loop, every created closure references the same name, so after the loop finishes they all see the final value. Beginners often try list comprehensions or \`map\` with side effects to work around it, but the cleanest fix is a default argument because defaults are evaluated at definition time and therefore capture each iteration's value. For multiple captured variables, explicit default arguments per variable remain more reliable than \`functools.partial\` for complex signatures.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-10T04:49:49.406592+00:00— report_created — created