Why do all these lambdas return the same number?
Question
This code builds three callbacks, one for each number. Predict what it prints.
Then fix it so it prints [0, 1, 2], and explain why the original version doesn't.
callbacks = [lambda: i for i in range(3)] print([f() for f in callbacks])
Show hints (3)
- "WHEN IS I READ"
The lambda's body doesn't run when the lambda is created. So when is
iread, and what isiat that moment? - "ONE SHARED VARIABLE"
All three lambdas refer to the same variable
i. After the loop it holds 2. Each function needs to keep its own value. - "STORE THE VALUE NOW"
Default argument values are computed when the function is created. Try
lambda i=i: i. Or create each lambda inside a separate function call, so each one gets its own variable.
Show checked explanation
It prints [2, 2, 2]. The lambdas capture the variable i, not its value, and read it only when called. By then the loop has finished and i is 2. To keep each value, store it when each function is created: a default argument lambda i=i: i, a factory function, or functools.partial.
def make_callback(n): return lambda: n # Fix 1: the default value is computed when each lambda is created callbacks = [lambda i=i: i for i in range(3)] print([f() for f in callbacks]) # Fix 2: each factory call has its own n callbacks = [make_callback(i) for i in range(3)] print([f() for f in callbacks])
[0, 1, 2] [0, 1, 2]
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Each lambda is a closure: a function that remembers variables from the place where it was created. It remembers the variable i itself, not the value i had at that moment.
| step | what happens | i is |
|---|---|---|
| loop pass 1 | lambda 1 created, linked to i | 0 |
| loop pass 2 | lambda 2 created, linked to the same i | 1 |
| loop pass 3 | lambda 3 created, linked to the same i | 2 |
| call all three | each lambda reads i now | 2 |
All three lambdas share one variable. Python reads it only when a lambda is called. This is called late binding. By then the loop has finished and i is 2, so you get [2, 2, 2].
The default argument fixes this because default values are computed once, when the function is created. lambda i=i: i copies the current value into the lambda's own parameter. So the three lambdas hold 0, 1 and 2.
The factory works for a different reason. Each call to make_callback(i) gets its own local variable n. The returned lambda remembers that n, and nothing changes it later.
A plain for loop that appends lambdas has the same bug. The cause is late binding, not the comprehension or the lambda keyword.
Common mistakes
- Blaming
lambda. A nesteddefcreated in the same loop capturesithe same way, and all three functions return 2. - Testing each callback inside the loop. There
f()returns the right number, becauseistill holds the current value. The bug only shows when you call the functions after the loop. - Using the default-argument fix in a function other people call. The extra parameter is public:
callbacks[0](10)returns 10 instead of 0. A factory orpartialhas no such parameter.
Follow-up questions
- "Can you fix it with
functools.partial?" Yes, when the lambda just passesito another function.[lambda: greet(i) for i in range(3)]has the same bug.[partial(greet, i) for i in range(3)]fixes it, becausepartialstores the argument values when it is created. - "What does
nonlocaldo?" It lets an inner function assign to a variable of the outer function. Reading works without it. Butcount += 1in the inner function makescountlocal, so the first call raisesUnboundLocalError. Withnonlocal count, the counter keeps counting between calls: 1, 2, 3.
What a strong answer covers
Predicts [2, 2, 2] before running the code and says closures capture variables, not values. Gives two fixes and why each works, and knows nonlocal is only needed to assign to an outer variable, not to read it.
Open in interactive practice deck →