Code Explanation:
1. Function make_funcs()
return [lambda: i for i in range(3)]
This creates a list of 3 lambda functions: lambda: i
All these lambdas refer to the same variable i, not its value at that time.
In the list comprehension, i goes from 0 → 1 → 2, but each lambda still just says "return i".
Important: Lambdas capture i by reference, not by value.
That means they all share the final value of i.
2. After make_funcs() is called:
funcs = make_funcs()
funcs is now a list of 3 lambda functions.
All of them will return the current value of i when they're called.
By the end of the loop, i == 2.
3. Calling the lambdas:
results = [f() for f in funcs]
Each lambda is called:
f1() → returns 2
f2() → returns 2
f3() → returns 2
Final Output:
[2, 2, 2]
.png)

0 Comments:
Post a Comment