Here's a Python puzzle that shows up in interviews, and in real bugs:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
You'd expect [0, 1, 2]. Python prints:
[2, 2, 2]
This is late binding, and it isn't just a lambda trivia question. It breaks button callbacks, dictionaries of handlers and threads started in a loop. Every example below was run on Python 3.15.
Prefer video? Here's the 3-minute version:
Why it happens: closures capture the variable, not the value
A function that uses a variable from an outer scope doesn't copy its value. It keeps a reference to the variable itself, and looks it up when it's called:
>>> x = 1
>>> f = lambda: x
>>> x = 99
>>> f()
99
In a loop there is only one variable i, and all three lambdas point to it. You can prove they share the same closure cell:
>>> funcs = [lambda: i for i in range(3)]
>>> funcs[0].__closure__[0] is funcs[2].__closure__[0]
True
>>> funcs[0].__closure__[0].cell_contents
2
By the time you call the lambdas, the loop has finished and i is 2. So all of them return 2.
(A regular for loop behaves the same way. The only difference is that the comprehension's i doesn't leak into the surrounding scope afterwards.)
Where it bites in real code
Nobody writes lambda: i for fun. But people write this all the time:
handlers = {}
for name in ["save", "open", "quit"]:
handlers[name] = lambda: print(f"clicked {name}")
handlers["save"]()
clicked quit
Every handler prints the last name. The same happens with GUI button callbacks (Tkinter's command=lambda: ...) and with threads:
import threading, time
out = []
threads = []
for i in range(3):
t = threading.Thread(target=lambda: (time.sleep(0.05), out.append(i)))
threads.append(t)
t.start()
for t in threads:
t.join()
print(sorted(out)) # [2, 2, 2]
Fix 1: a default argument (i=i)
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
Default values are evaluated once, when the function is created, so each lambda stores its own copy of the current i.
It's the classic fix, but it's a bit of a hack: the function now has a parameter that callers can override by accident:
funcs[0](42) # 42
Fix 2: functools.partial
partial binds the argument immediately, and it reads clearly:
from functools import partial
def show(n):
return n
funcs = [partial(show, i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
For the handlers example it's a one-liner:
handlers[name] = partial(print, "clicked", name)
handlers["save"]() # clicked save
Fix 3: a factory function
def make(n):
return lambda: n
funcs = [make(i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
Each call to make() creates a new scope with its own n, so each lambda closes over a different variable. This is the most explicit option, and it's handy when the inner function is more than one line.
Recap
- Closures capture the variable, not its value
- The value is looked up when the function is called, which is usually after the loop has ended
- It bites callbacks, handler dicts and threads created in loops
- Fixes:
lambda i=i: i(quick),functools.partial(fn, i)(clean), or a factory function (explicit)
Has this one ever bitten you? Tell me in the comments 👇
I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.
Top comments (0)