🔍 Step 1: What does the loop do?
for i in range(3):
range(3) → 0, 1, 2
So the loop runs 3 times.
Each time we append:
lambda x: x + i
So it looks like we are creating:
x + 0
x + 1
x + 2
But… ❗ that’s NOT what actually happens.
🔥 The Important Concept: Late Binding
Python does not store the value of i at the time the lambda is created.
Instead, the lambda remembers the variable i itself, not its value.
This is called:
🧠 Late Binding
The value of i is looked up when the function is executed, not when it is created.
After the Loop Finishes
After the loop ends:
i = 2
The loop stops at 2, so the final value of i is 2.
Now your list funcs contains 3 functions, but all of them refer to the SAME i.
Effectively, they behave like:
lambda x: x + 2
lambda x: x + 2
lambda x: x + 2
🚀 Now Execution Happens
[f(10) for f in funcs]
Each function is called with 10.
Since i = 2:
10 + 2 = 12
For all three functions.
✅ Final Output
[12, 12, 12]
🎯 How To Fix It (Capture Current Value)
If you want expected behavior (10, 11, 12), do this:
funcs = []
for i in range(3):
funcs.append(lambda x, i=i: x + i)
print([f(10) for f in funcs])
Why this works?
i=i creates a default argument, which stores the current value of i immediately.
Now output will be:
[10, 11, 12]
💡 Interview Tip
If someone asks:
Why does Python give [12,12,12]?
Say confidently:
Because of late binding in closures — lambdas capture variables, not values.


0 Comments:
Post a Comment