- Home
- Interview Questions
- Python
- Why do lambdas created inside a loop all return the last loo…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: Python closures use late binding. They look up the loop variable when the function is called, not when it is created, so after the loop ends every lambda sees the final value. Fix it by binding the current value at creation time with a default argument, functools.partial or a factory function.
Detailed explanation
Three facts explain this behaviour:
- Loops do not create a new scope. In Python, a
forloop reuses one variable in the enclosing scope, such as the function or module. Each iteration rebinds the same name. The variable still exists after the loop ends. - Closures capture variables, not values. A lambda or nested function that uses
istores a reference to the variableiin the enclosing scope, through a cell object. It does not copy the value thatihad at that moment. - Lookup happens at call time. When you call the lambda later, Python reads the current value of
i. By then the loop has finished, so every lambda gets the last value.
List comprehensions in Python 3 have their own scope, but this does not help. The comprehension still has one variable that is rebound on every iteration, and all lambdas created inside it share that variable.
The fixes all work by evaluating the value at creation time:
- Default argument:
lambda i=i: i. Default values are evaluated once, when the function is defined, so each lambda stores its own copy. This is the most common idiom. - functools.partial: binds the argument value right away. It is clearer when the function is not a lambda.
- Factory function: a function that takes the value as a parameter and returns the inner function. Each call creates a new scope with its own variable.
In real code, this bug shows up when registering GUI button callbacks, building lists of handlers, scheduling tasks with threading or asyncio, and creating Django or Flask route functions dynamically.
Example
# The bug
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
# Fix 1: default argument binds value at definition time
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
# Fix 2: functools.partial
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]
# Fix 3: factory function creates a new scope per call
def make_handler(n):
def handler():
return n
return handler
funcs = [make_handler(i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
# Proof that the closure reads the variable at call time
def demo():
fs = []
for i in range(3):
fs.append(lambda: i)
i = 100
return [f() for f in fs]
print(demo()) # [100, 100, 100]
The last example is the clearest proof. Changing i after the loop changes what every lambda returns.
Common mistakes
- Blaming lambda. A normal
definside the loop behaves the same way. The cause is the closure, not the lambda syntax. - Assuming comprehensions fix it. Their separate scope stops the variable from leaking out, but all closures created inside still share one variable.
- Using the default-argument fix on public APIs. A caller can pass a value and override
iby accident. In shared code,partialor a factory function is safer. - Confusing this with mutable default arguments. Here, early evaluation of defaults is the solution. With
def f(x=[]), the same early evaluation causes the bug.
Follow-up questions
- How can you inspect what a closure has captured, for example using
__closure__andcell_contents? - When would you need
nonlocalinside a nested function, and how is it different from this case? - Does the loop variable still exist after a
forloop, and what about after a list comprehension?
Interview tip: Explain the cause as "closures capture the variable, not the value," then show the default-argument fix and one cleaner alternative such as partial.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard Python questions
Related Questions
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · Java · 1 ans
- What makes an interface a functional interface, and what does @FunctionalInterface actually do? · Java · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- How does the else clause work with for and while loops in Python? · Python · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)