Unraveling Why Python’s Lambda Returns [6,6,6,6] – A Closure Deep Dive
This article explains a Python puzzle where a list of lambda functions unexpectedly returns [6,6,6,6] due to late binding in closures, walks through the code, debugging screenshots, and clarifies how closures capture loop variables in Python.
Preface
Today we discuss a Python question raised in a chat group. The problem involves understanding the output of a small program.
Interesting Problem
Problem: Write the output of the following program.
def multipliers():
return [lambda x: i*x for i in range(4)]
print([m(2) for m in multipliers()])Correct answer: [6, 6, 6, 6] At first glance it looks like a simple lambda, but the result is surprising because of how closures capture the loop variable.
Analysis of the Code
The first function uses a list comprehension to create four lambda functions that multiply their argument by i. This can be rewritten as:
squares = []
for i in range(4):
res = lambda x: i*x
squares.append(res)Each lambda closes over the variable i. However, the lambdas are not executed until the second line, after the loop has finished, so i has the final value 3.
Debugging screenshots illustrate the execution flow: the debugger stops inside multipliers, steps through the loop, and finally evaluates each lambda with x=2, producing 3*2 = 6 for every call.
Because the loop has already completed, all four lambdas reference the same final value of i, resulting in [6, 6, 6, 6].
Conclusion
This example shows how late binding in Python closures can lead to unexpected results, and why it is important to understand the underlying mechanics of lambda functions and variable scope.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
