Explanation:
Initialize i
i = 0
The variable i is set to 0.
It will be used as the counter for the while loop.
Create an empty list
funcs = []
funcs is an empty list.
We will store lambda functions inside this list.
Start the while loop
while i < 5:
The loop runs as long as i is less than 5.
So the loop will execute for: i = 0, 1, 2, 3, 4.
Append a lambda that captures the current value of i
funcs.append(lambda i=i: i)
Why is i=i important?
i=i is a default argument.
Default arguments in Python are evaluated at the moment the function is created.
So each lambda stores the current value of i during that specific loop iteration.
What values get stored?
When i = 0 → lambda stores 0
When i = 1 → lambda stores 1
When i = 2 → lambda stores 2
When i = 3 → lambda stores 3
When i = 4 → lambda stores 4
So five different lambdas are created, each holding a different number.
Increment i
i += 1
After each iteration, i increases by 1.
This moves the loop to the next number.
Call all lambda functions and print their outputs
print([f() for f in funcs])
What happens here?
A list comprehension calls each stored lambda f() in funcs.
Each lambda returns the value it captured earlier.
Final Output:
[0, 1, 2, 3, 4]


0 Comments:
Post a Comment