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.

PythonData Integrity

Code

pythonsnippet
20 lines
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

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`.