Explanation:
๐น Step 1: Create Empty List
x = []
An empty list is created:
[]
This list will store lambda functions.
๐น Step 2: Start Loop
for i in range(3):
range(3) gives:
0,1,2
Loop runs 3 times.
๐น Step 3: First Iteration
i = 0
Execute:
x.append(lambda: i)
Lambda created:
lambda: i
⚠️ Important:
Lambda does NOT store current value immediately ๐
It stores REFERENCE to variable i.
List now:
[lambda]
๐น Step 4: Second Iteration
i = 1
Another lambda added:
lambda: i
List now:
[lambda, lambda]
BUT both lambdas still reference SAME variable:
i
๐น Step 5: Third Iteration
i = 2
Third lambda added.
List becomes:
[lambda, lambda, lambda]
All lambdas reference SAME final variable:
i
๐น Step 6: Loop Ends
After loop finishes:
i = 2
⚠️ Final value survives outside loop ๐
๐น Step 7: Access x[1]
x[1]
This gives second lambda function.
Then:
x[1]()
calls lambda.
Lambda checks CURRENT value of:
i
Current value:
2
So:
x[1]() → 2
๐น Step 8: Print Result
print(2)
๐ Final Output:
2
๐ฅ Final Output
2

0 Comments:
Post a Comment