Python Lambda Loops: Understanding Late Binding

How Lambda Really Works Inside Python Loops One of the most confusing Python behaviors appears when using lambda inside loops. Let’s look at this example: funcs = [lambda x: x * i for i in range(3)] print(funcs[1](2)) Many developers expect the output to be 2, but the actual output is: 4 Let’s break it down step by step. 1️⃣ Step 1: What does this line create? funcs = [lambda x: x * i for i in range(3)] This is a list comprehension. The loop runs with: • i = 0 • i = 1 • i = 2 On each iteration, we append: lambda x: x * i After the loop finishes, funcs contains three function objects. Important: ❌ It does NOT contain numbers. ✅ It contains function objects. If we print it: print(funcs) ➡️ We get something like: [<function ...>, <function ...>, <function ...>] Because we stored functions, not results. 2️⃣ Step 2: The Critical Concept: Late Binding Here’s the key idea: The lambda does not store the value of i at the time it is created. It stores a reference to the variable i. ➡️ By the time the loop finishes, i equals: 2 So all three functions now effectively behave like: lambda x: x * 2 This behavior is called late binding. Python looks up the value of i when the function is executed, not when it is defined. 3️⃣ Step 3: What does this line do? print(funcs[1](2)) First: funcs[1] Returns the second function in the list. Which is effectively: lambda x: x * 2 Then (2) ➡️ Calls the function with x = 2. So the result becomes: 2 * 2 = 4 That’s why the output is: 4 🔑 Key Points to Remember • lambda creates a function. • The loop creates several functions. • They all use the same variable. • After the loop ends, the variable has its last value. • So all functions use that last value. • If you want each function to remember its own value, you must store it at creation time using: ➡️ lambda x, i=i: x * i Understanding this concept is essential when working with closures, functional programming, or building dynamic logic in Python. Have you ever been surprised by Python’s late binding behavior? 👀 #Python #Programming #Coding #SoftwareDevelopment #AI #MachineLearning #DataScience

To view or add a comment, sign in

Explore content categories