Code Explanation:
Step 1: make_multipliers() creates lambdas in a loop
[lambda x: x * i for i in range(3)]
At each iteration, a lambda is added to the list.
But all lambdas capture the same variable i, which keeps changing in the loop.
After the loop ends, i = 2, so all lambdas refer to i = 2.
Step 2: Store in funcs
Now funcs is a list of 3 lambdas, each of which does:
lambda x: x * i # where i is 2 for all of them
Step 3: Call each lambda with x = 2
results = [f(2) for f in funcs]
Each f is essentially:
lambda x: x * 2
So all return 2 * 2 = 4.
Output
[4, 4, 4]
.png)

0 Comments:
Post a Comment