Code Explanation:
Line 1 – Create an empty list
funcs = []
Initializes an empty list named funcs.
This list will be used to store functions (lambdas).
Lines 2–3 – Append lambdas inside a loop
for i in range(3):
funcs.append(lambda: i)
range(3) gives i = 0, 1, 2
Each time, a lambda function is created and added to the list.
BUT: The lambda captures i by reference, not value.
This means all the lambdas share the same i, which changes during each loop iteration.
After the loop ends, i = 2, and all lambdas "remember" that final value.
Line 4 – Call all stored functions
results = [f() for f in funcs]
This calls each lambda in funcs.
Since all lambdas reference the same variable i, and i == 2 after the loop:
Each f() returns 2
Line 5 – Print the result
print(results)
Output:
[2, 2, 2]
.png)

0 Comments:
Post a Comment