Fundamentals 4 min read

Why Python Closures Print 6,6,6,6 and How to Get 0,2,4,6

An unexpected Python interview question demonstrates how late binding in closures causes all lambdas to use the final loop value, producing 6,6,6,6 instead of 0,2,4,6, and the article explains the underlying reason and presents four practical solutions to achieve the intended output.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Python Closures Print 6,6,6,6 and How to Get 0,2,4,6

Accidentally encountered 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))

Many assume the output is 0,2,4,6, but the actual result is 6,6,6,6 due to Python's late binding in closures.

Late binding means the variable i is looked up when the inner function is called, after the loop has finished, so i equals its final value 3 for all lambdas, producing 3*2 = 6.

To obtain the expected 0,2,4,6, you can bind the current value of i at definition time. Four solutions are presented:

Solution 1: Use default argument to capture i

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: Use functools.partial

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: Use a generator expression

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 with lazy evaluation

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

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

All four approaches produce the desired output 0,2,4,6.

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.

PythonLambdacoding interviewfunctionclosureslate 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.