Code Explanation:
1. Initialization
funcs = []
What it does:
Initializes an empty list called funcs.
This list will hold lambda functions.
2. Loop to Create Functions
for i in range(5):
What it does:
Starts a for loop that runs 5 times, with i taking values from 0 to 4.
Purpose:
For each value of i, the code creates a lambda function that captures that value.
3. Creating Lambda Functions with Default Arguments
funcs.append(lambda x=i: x)
What it does:
Defines a lambda function: lambda x=i: x
x=i sets a default argument, capturing the current value of i at that iteration.
Then, the lambda is appended to the funcs list.
Why it works:
In Python, default arguments are evaluated at the time of function definition, not when the function is called.
This prevents the common issue where lambdas inside loops all reference the same final value.
Example (what's really being created):
1st loop: lambda x=0: x → stores 0
2nd loop: lambda x=1: x → stores 1
5th loop: lambda x=4: x → stores 4
4. Calling Each Function
print([f() for f in funcs])
What it does:
Uses a list comprehension to call each lambda function stored in funcs.
Since each lambda has a default x, we call f() with no arguments.
Each f() returns the value of x it captured earlier.
Iteration-wise behavior:
funcs[0]() → x=0 → returns 0
funcs[1]() → x=1 → returns 1
funcs[4]() → x=4 → returns 4
5. Final Output
[0, 1, 2, 3, 4]
.png)

0 Comments:
Post a Comment