Code Explanation:
Function Definition
def f(x, y=[]):
for i in range(x):
y.append(i)
return y
Parameters:
x: How many numbers to append (from 0 to x-1)
y: A list to which numbers will be appended. Default is a mutable list []
Function Calls
Call 1:
print(f(2))
x = 2, y not passed → uses shared default list.
Loop appends 0, 1 → y = [0, 1]
Returns: [0, 1]
Call 2:
print(f(3, []))
x = 3, y = [] → a new list is passed explicitly.
Loop appends 0, 1, 2 → y = [0, 1, 2]
Returns: [0, 1, 2]
This one is isolated from the shared default list.
Call 3:
print(f(2))
x = 2, y not passed → again uses the shared default list, which already contains [0, 1] from Call 1.
Appends 0, 1 again → y = [0, 1, 0, 1]
Returns: [0, 1, 0, 1]
Final Output:
[0, 1]
[0, 1, 2]
[0, 1, 0, 1]


0 Comments:
Post a Comment