Code Explanation:
๐น 1. Initializing the List
funcs = []
An empty list funcs is created
This list will store functions
๐น 2. Starting the Loop
for i in range(3):
Loop runs 3 times with values:
i = 0, 1, 2
๐น 3. Defining the Function Inside Loop
def f():
return i
A function f is defined in each iteration
⚠️ Important: The function does not store the current value of i immediately
Instead, it refers to i (late binding)
๐ This means:
All functions will look up i when they are called, not when they are created
๐น 4. Appending Function to List
funcs.append(f)
The function f is added to the list
After loop ends, funcs contains 3 functions
๐น 5. After Loop Ends
Final value of i is:
i = 2
All functions refer to this same i
๐น 6. Calling the Functions
print([f() for f in funcs])
Each function is called one by one
Each function returns the current value of i, which is 2
๐น ✅ Final Output
[2, 2, 2]

0 Comments:
Post a Comment