Code Explanation:
1️⃣ Creating an Empty List
funcs = []
Explanation
An empty list funcs is created.
It 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 Function Inside Loop
def f():
return i * i
Explanation ⚠️
A function f is defined in each iteration.
It returns i * i.
❗ BUT:
It does not store the value of i at that time.
It stores a reference to variable i (not value).
4️⃣ Appending Function to List
funcs.append(f)
Explanation
The function f is added to the list.
This happens 3 times → list contains 3 functions.
๐ All functions refer to the same variable i.
5️⃣ Loop Ends
After loop completes:
i = 2
6️⃣ Creating Result List
result = []
Explanation
Empty list to store outputs.
7️⃣ Calling Each Function
for fn in funcs:
result.append(fn())
Explanation
Each stored function is called.
When called, each function evaluates:
i * i
๐ But current i = 2
So:
2 * 2 = 4
This happens for all 3 functions.
8️⃣ Printing Result
print(result)
๐ค Final Output
[4, 4, 4]

0 Comments:
Post a Comment