Fundamentals 5 min read

Why Does This Python Lambda Loop Print 6 Every Time? Mastering Late Binding

The article examines a Python interview question where a lambda list inside a loop unexpectedly prints 6 for all elements due to late binding in closures, explains the underlying mechanism, and presents four practical solutions—including default‑argument binding, functools.partial, generator expressions, and yield‑based approaches—to achieve the intended 0, 2, 4, 6 output.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Does This Python Lambda Loop Print 6 Every Time? Mastering Late Binding

I stumbled upon a Python interview question: what does the following code output?

def testFun():
    temp = [lambda x : i*x for i in range(4)]
    return temp

for everyLambda in testFun():
    print (everyLambda(2))

My initial guess was the obvious sequence:

0
2
4
6

However, the actual answer was:

6
6
6
6

Running the code confirmed the latter result, which led me to realize the cause: Python’s closures use late binding, meaning the variable i is looked up when the inner function is called, not when it is defined. By the time the lambdas are invoked, the for loop has finished and i holds its final value 3, so each lambda computes 3 * 2 = 6.

To obtain the expected output 0, 2, 4, 6, we need to bind the current value of i at definition time. Below are four solutions.

Solution 1: Use a default argument to capture the current value.

def testFun():
    temp = [lambda x, i=i: i*x for i in range(4)]
    return temp

for everyLambda in testFun():
    print (everyLambda(2))

Solution 2: Employ functools.partial to fix the multiplier.

from functools import partial
from operator import mul

def testFun():
    return [partial(mul, i) for i in range(4)]

for everyLambda in testFun():
    print (everyLambda(2))

Solution 3: Write a generator expression that creates the lambdas with immediate binding.

def testFun():
    return (lambda x, i=i: i*x for i in range(4))

for everyLambda in testFun():
    print (everyLambda(2))

Solution 4: Use yield to produce lambdas lazily, avoiding the late‑binding pitfall.

def testFun():
    for i in range(4):
        yield lambda x: i*x

for everyLambda in testFun():
    print (everyLambda(2))

The final execution produces the desired sequence:

These solutions demonstrate that the interview question tests the candidate’s understanding of Python closures and the late‑binding behavior, and provides multiple ways to achieve the correct result.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Lambdaclosuresinterview questionlate binding
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.