Code Explanation:
Function Definition: make_funcs
This defines a function that will return a list of functions.
def make_funcs():
Initialize an Empty List
We initialize an empty list named funcs to store lambda functions.
funcs = []
Loop from 0 to 3
The loop runs 4 times with i taking values from 0 to 3.
for i in range(4):
Create a Closure with Default Argument
funcs.append(lambda x=i: lambda: x*i)
This is the trickiest part:
x=i is a default argument, which captures the current value of i at each iteration.
lambda x=i: returns another lambda: lambda: x*i.
So funcs will store inner lambdas, each remembering the value of i when they were created.
Return List of Inner Lambdas
return [f() for f in funcs]
Each f() returns the inner lambda (i.e., lambda: x*i).
So this returns:
[
lambda: 0*0,
lambda: 1*1,
lambda: 2*2,
lambda: 3*3
]
Call Each Inner Lambda
for f in make_funcs():
print(f())
We now:
Call make_funcs() → get a list of 4 inner lambdas.
Call each of them with f(), which evaluates x*i from before.
Intermediate Evaluation
lambda: 0*0 → 0
lambda: 1*1 → 1
lambda: 2*2 → 4
lambda: 3*3 → 9
Final Output
0
1
4
9
.png)

0 Comments:
Post a Comment