1. Home
  2. Interview Questions
  3. Python
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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:

  1. Loops do not create a new scope. In Python, a for loop 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.
  2. Closures capture variables, not values. A lambda or nested function that uses i stores a reference to the variable i in the enclosing scope, through a cell object. It does not copy the value that i had at that moment.
  3. 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 def inside 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 i by accident. In shared code, partial or 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__ and cell_contents?
  • When would you need nonlocal inside a nested function, and how is it different from this case?
  • Does the loop variable still exist after a for loop, 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

All hard questions →

Related Questions

‹
Q2 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA