Step-by-Step Explanation
✅ 1. Create an Empty List
funcs = []This list will store functions (lambdas).
✅ 2. Loop Runs 3 Times
for i in range(3):The values of i will be:
0 → 1 → 2✅ 3. Lambda Is Appended Each Time
funcs.append(lambda: i)⚠️ Important:
You are NOT storing the VALUE of i,
You are storing a function that will return i later.
So after the loop:
funcs[0] → returns i
funcs[1] → returns i
funcs[2] → returns i
All three lambdas refer to the SAME variable i.
✅ 4. Final Value of i
After the loop finishes:
i = 2✅ 5. Calling All Functions
print([f() for f in funcs])This executes:
f() → returns i → which is 2So all functions return:
[2, 2, 2]✅ ✅ Final Output
[2, 2, 2]Why This Happens? (Late Binding)
Python lambdas:
-
Do NOT remember the value
-
They remember the variable reference
-
Value is looked up only when the function is called
This behavior is called Late Binding.
✅ ✅ ✅ Correct Way (Fix This Problem)
✅ Solution 1: Use Default Argument
✅ Output:
[0, 1, 2]Why this works:
i=i captures the value immediately
-
Each lambda stores its own copy


0 Comments:
Post a Comment