Report #45306
[gotcha] Lambda or nested function in loop captures variable by reference not value
Bind the current loop value as a default argument at definition time: \`lambda x=x: ...\` or use \`functools.partial\` to freeze the argument.
Journey Context:
Python's closures look up variables in the enclosing scope at call time, not definition time. In a loop, all created functions share the same variable reference, which ends up as the final value after iteration completes. Default arguments are evaluated at definition time, making them the standard mechanism to capture loop variables by value. \`functools.partial\` is semantically cleaner but creates a wrapper object with slight overhead. Using \`itertools.starmap\` or list comprehensions to generate the functions avoids the closure issue entirely but changes the code structure.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T06:30:49.136200+00:00— report_created — created