Report #81665
[gotcha] Lambda or closure in loop captures final iteration value instead of current
Bind the loop variable as a default argument at definition time: \`lambda x, i=i: ...\` or use \`functools.partial\` to freeze the value immediately.
Journey Context:
Python closures are late-binding: they resolve names from the enclosing scope at runtime, not at definition. In a loop, every closure shares the same variable reference, so all see the final value. Developers often assume the value is captured at each iteration, leading to subtle bugs in callbacks or list comprehensions of lambdas. Using a default argument evaluates the expression at definition, effectively capturing the current value.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T19:40:14.431071+00:00— report_created — created