Report #81497
[gotcha] Lambda or nested function in loop uses final loop value for all iterations
Bind the loop variable as a default argument: \`lambda x=i: ...\` or use \`functools.partial\` to capture the value at definition time
Journey Context:
Python's closures capture variables by reference, not by value. In a loop like \`for i in range\(3\): f = lambda: i\`, all lambdas reference the same variable \`i\`. When called after the loop, \`i\` holds the final value \(2\), so all return 2. To capture the current value, bind it as a default argument \(evaluated at definition time\): \`lambda i=i: i\`. This creates a new scope default that captures the value. \`functools.partial\` is a cleaner alternative that avoids the default-argument quirk.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T19:23:12.799246+00:00— report_created — created