Code Explanation:
๐น 1. Creating an Empty List
funcs = []
✅ Explanation:
An empty list named funcs is created.
This list will store lambda functions.
Current state:
[]
๐น 2. Starting the Loop
for i in range(3):
✅ Explanation:
range(3) generates:
0, 1, 2
The loop runs 3 times.
๐น 3. First Iteration (i = 0)
funcs.append(lambda: i)
✅ Explanation:
A lambda function is created:
lambda: i
and stored in the list.
Current List
[
lambda: i
]
⚠️ Important:
The lambda does not store the value 0.
It stores a reference to variable i.
๐น 4. Second Iteration (i = 1)
Again:
funcs.append(lambda: i)
Current list:
[
lambda: i,
lambda: i
]
Again, both lambdas refer to the same variable i.
๐น 5. Third Iteration (i = 2)
Again:
funcs.append(lambda: i)
Current list:
[
lambda: i,
lambda: i,
lambda: i
]
๐น 6. Loop Ends
After the loop finishes:
i = 2
⚠️ Very Important
There is only one variable i.
All lambdas point to this same variable.
Final value:
2
๐น 7. First Function Call
print(funcs[0]())
What happens?
Python executes:
lambda: i
Current value of i:
2
So result:
2
Printed:
2
๐น 8. Second Function Call
print(funcs[2]())
What happens?
Third lambda is also:
lambda: i
Current value of i is still:
2
Result:
2
Printed:
2
๐ฏ Final Output
2
2

0 Comments:
Post a Comment