Report #103834
[gotcha] Loop-created lambdas or nested functions all capture the same final variable
Bind the loop variable as a default argument at definition time: \`\[lambda x=i: x for i in range\(3\)\]\`. For more complex cases use \`functools.partial\`. Defaults are evaluated early; free variables are resolved late.
Journey Context:
Python closures look up free variables when the function runs, not when it is defined. A for-loop does not create a new scope for its control variable, so every lambda references the same name. By the time the functions execute, the loop has finished and the variable holds the last value. Passing \`x=i\` as a default captures the current iteration value because defaults are evaluated at definition time. \`functools.partial\` works too but default arguments are the standard idiom for simple closures.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-13T04:47:14.738502+00:00— report_created — created