Report #87169
[gotcha] Lambdas or nested functions created inside a loop all capture the final loop variable value
Bind the current value at definition time with a default argument: \`lambda x=x: ...\`; this also works for plain nested \`def\` functions
Journey Context:
Python closures use late binding: free variables are looked up when the function is called, not when it is defined. In a loop, every closure captures the same name \`x\`, so by the time any of them run, \`x\` holds the final value. This is not specific to lambdas; regular nested functions behave the same way. The \`x=x\` idiom works because default arguments are evaluated at definition time, freezing the value in a local parameter. Alternatives include list comprehensions/generators that produce immediately-resolved values or \`functools.partial\`. Many tutorials only show the lambda case, so the bug resurfaces as soon as someone refactors to a named inner function.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T04:54:18.305547+00:00— report_created — created