Report #3835
[gotcha] Lambdas or nested functions defined in a loop all capture the final iteration's variable value
Bind the loop variable as a default argument to freeze the value at definition time: \`lambda x=x: ...\` or use \`functools.partial\` to capture the current value.
Journey Context:
Python closures capture variables by reference \(the cell object\), not by value. When the loop finishes, the closure sees the final state of the variable. Default arguments are evaluated at function definition time, not call time, making them the idiomatic mechanism to capture the loop variable's current value. Rebiding the variable inside the lambda fails because it still references the same enclosing cell. Alternatives like list comprehensions or partial function application work but are less idiomatic than the default-argument pattern.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T18:18:04.841473+00:00— report_created — created