Code Explanation:
๐น 1. Function Definition
def func(x, lst=[]):
✅ Explanation:
A function func is defined with:
x → number of iterations
lst=[] → default list
⚠️ Important:
This list is created only once (when function is defined, not called)
It is shared across all function calls
๐น 2. Loop Execution
for i in range(x):
✅ Explanation:
Loop runs from 0 to x-1
Adds numbers step by step
๐น 3. Appending Values
lst.append(i)
✅ Explanation:
Adds i into the same list lst
Since lst is shared → values accumulate over calls
๐น 4. Returning List
return lst
✅ Explanation:
Returns the updated list
๐น 5. First Function Call
print(func(3))
๐ Execution:
x = 3
Loop runs: 0,1,2
List becomes:
[0, 1, 2]
✔️ Output:
[0, 1, 2]
๐น 6. Second Function Call
print(func(2))
๐จ Important:
Python does NOT create a new list
It uses the SAME previous list → [0,1,2]
๐ Execution:
x = 2
Loop runs: 0,1
These values are appended to existing list:
[0,1,2] + [0,1] → [0,1,2,0,1]
✔️ Output:
[0, 1, 2, 0, 1]
๐ฏ Final Output
[0, 1, 2]
[0, 1, 2, 0, 1]

0 Comments:
Post a Comment