Report #6297
[gotcha] Lambda or default argument in loop captures final loop variable instead of current iteration
Bind the loop variable as a default argument at definition time: \`lambda x=i: ...\` or use \`functools.partial\`. Do not rely on closure variable lookup in loops without immediate binding.
Journey Context:
Python closures look up variables by name at call time, not definition time. In a loop, all iterations share the same scope, so when the loop finishes, all closures see the final value. Binding via default arguments evaluates the expression at definition time, creating the needed snapshot. Alternatives like \`partial\` or factory functions work but default args are the most idiomatic for lambdas. This is a language design tradeoff \(late binding\) vs early binding languages.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:43:36.132557+00:00— report_created — created