Code Explanation:
๐น 1. Creating Empty List
funcs = []
✅ Explanation:
An empty list named funcs is created.
This list will store lambda functions.
Current state:
funcs = []
๐น 2. Starting Loop
for i in range(3):
✅ Explanation:
range(3) generates:
0, 1, 2
Loop runs 3 times.
๐น 3. First Iteration (i = 0)
funcs.append(lambda x: x + i)
✅ Explanation:
A lambda function is created:
lambda x: x + i
and stored in the list.
⚠️ Important:
The lambda does not store the value 0.
It stores a reference to variable i.
Current list:
[
lambda x: x + i
]
๐น 4. Second Iteration (i = 1)
Again:
funcs.append(lambda x: x + i)
Another lambda is added.
Current list:
[
lambda x: x + i,
lambda x: x + i
]
๐น 5. Third Iteration (i = 2)
Again:
funcs.append(lambda x: x + i)
Current list:
[
lambda x: x + i,
lambda x: x + i,
lambda x: x + i
]
๐น 6. Loop Ends
After loop finishes:
i = 2
✅ Important:
There is only one variable i.
All lambdas refer to the same variable.
Final value of i:
2
๐น 7. First Function Call
print(funcs[0](10))
๐ What happens?
First lambda:
lambda x: x + i
receives:
x = 10
Current value of:
i = 2
Calculation:
10 + 2
Result:
12
Printed:
12
๐น 8. Second Function Call
print(funcs[1](10))
๐ What happens?
Second lambda is:
lambda x: x + i
Again:
x = 10
i = 2
Calculation:
10 + 2
Result:
12
Printed:
12
๐ฏ Final Output
12
12

0 Comments:
Post a Comment