Code Explanation:
1. List Initialization
funcs = []
Creates an empty list named funcs.
This will store lambda functions.
2. For Loop to Append Lambdas
for i in range(3):
funcs.append(lambda: i)
Breakdown:
range(3) produces: 0, 1, 2
On each iteration:
A lambda function is created: lambda: i
This function returns the value of i when it's called later.
This lambda is added to the funcs list.
Important:
The lambda captures the variable i, not its value at that moment.
All 3 lambdas end up referring to the same i, which becomes 2 at the end of the loop.
So, this is not the same as storing lambda: 0, lambda: 1, and lambda: 2.
3. Call Each Lambda Function
for f in funcs:
print(f())
Now, we loop through each function in funcs and call it.
But recall: each lambda refers to the same variable i, which is now 2.
So, this prints:
2
2
2
Final Output
2
2
2
.png)

0 Comments:
Post a Comment