Python closures and late binding in lambdas

Backend Live Coding November 13, 2026 python

The lambdas close over the variable i, not its value at the time of creation (late binding).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# ======================================================================
# Q: What is a closure? What does the following code print?
#
# The lambdas close over the variable i, not its value at the time of creation
# (late binding). When they are called, i is 2. Fix: lambda i=i: i, which binds
# the value as a default argument, or functools.partial.
# ======================================================================

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])   # [2, 2, 2]