Code Explanation:
1. Function Definition: make_funcs()
def make_funcs():
return [lambda x: i * x for i in range(3)]
This function returns a list of 3 lambda functions.
Each lambda is defined as: lambda x: i * x
The loop for i in range(3) goes through i = 0, 1, 2
BUT: i is captured by reference, not value — this is called late binding.
2. Calling make_funcs()
funcs = make_funcs()
Now funcs is a list of three lambda functions, but all of them refer to the same i, which ends up being 2 after the loop finishes.
3. Evaluating the Lambdas
results = [f(2) for f in funcs]
Each f(2) now evaluates i * 2, but since i = 2 at the end of the loop:
f(2) = 2 * 2 = 4
All lambdas return 4
So results = [4, 4, 4]
4. Final Output
print(results)
Output:
[4, 4, 4]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment