Code Explanation:
1. Function outer() is called
funcs = []
An empty list is created to hold functions.
for i in range(3):
funcs.append(lambda: i)
Loop runs i = 0, 1, 2
In each iteration, it appends a lambda function that returns i.
BUT — this is the key point:
Lambdas do not capture the current value of i at the time they're created.
Instead, they capture the variable itself, not its value.
So after the loop finishes, i = 2, and all three lambdas refer to the same variable i, which now equals 2.
2. Returned Functions
f1, f2, f3 = outer()
The list of 3 lambda functions is returned.
All 3 functions are effectively: lambda: i, where i = 2 (final value after the loop)
3. Print the Results
print(f1(), f2(), f3())
Each function returns i, and since i = 2, the output is:
2 2 2
Final Output:
2 2 2


0 Comments:
Post a Comment