Closures In Loops Bind The Name Not The Value
A loop variable is captured by name, not by value, so late-running lambdas all see the final count; a default parameter pins the value at definition time.
Code
callbacks = []
for i in range(3):
# closure late binding: the loop variable is captured by name, not by value
callbacks.append(lambda: i)
print([f() for f in callbacks]) # 全部看到循环结束后的 2
fixed = []
for i in range(3):
# 修正:默认参数在定义时求值,把当时的 i 固定住
fixed.append(lambda i=i: i)
print([f() for f in fixed])
late = []
for i in range(3):
# 另一种修法:工厂函数每次调用产生新的作用域
late.append((lambda bound: lambda: bound)(i))
print([f() for f in late])Output
Captured from a sandboxed run of this snippet in the build pipeline.
[2, 2, 2]
[0, 1, 2]
[0, 1, 2]Reading the snippet
Iteration happens inside for i in range(3) — everything outside it runs once.
Top-level bindings callbacks, fixed, late hold the demo state — nothing sits inside a function scope.
Interactive Tools for This Topic
CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `callbacks`, `fixed`, `late`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.