Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

Python Closure Gotcha: Why Loop-Generated Lambdas All Return the Same Value

DEVLORE 1 min read

A common pitfall in Python arises when creating functions (like lambdas) inside a loop that reference the loop variable. All the functions capture the same variable reference, not its value at definition time. As a result, when called after the loop, they all return the final value of the variable.

For example, consider:

funcs = []
for i in range(3):
funcs.append(lambda: i)

print([f() for f in funcs])  # Output: [2, 2, 2]

To fix this, use a default argument to snapshot the variable's value:

funcs = []
for i in range(3):
funcs.append(lambda x=i: x)

print([f() for f in funcs])  # Output: [0, 1, 2]

Understanding Python's closure scoping is essential for robust code, especially when dynamically creating functions.

React