Code Explanation:
1️⃣ Creating an Empty List
funcs = []
Explanation
An empty list named funcs is created.
This list will store function objects.
2️⃣ Starting the Loop
for i in range(3):
Explanation
Loop runs 3 times.
Values of i:
0, 1, 2
3️⃣ Defining the Function Inside Loop
def f():
return i
Explanation
A function f is defined inside the loop.
It returns the variable i.
⚠️ Important:
The function does not store the value of i at creation time.
It stores a reference to the variable i.
4️⃣ Appending Function to List
funcs.append(f)
Explanation
The function f is added to the list.
This happens 3 times, so funcs contains 3 functions.
๐ But all functions refer to the same variable i.
5️⃣ Loop Ends
After loop finishes, the value of i becomes:
2
6️⃣ Calling Each Function
for fn in funcs:
print(fn())
Explanation
Each stored function is called.
When called, each function returns the current value of i.
๐ Since i = 2 after loop ends:
๐ค Final Output
2
2
2

0 Comments:
Post a Comment