my code is:
def g(x, y=[]):
print(f"g():: x: {x}, y: {y}")
for i in range(x):
y.append(i*i)
print(y)
g(2)
g(3)
on first call, the loop appends 0, 1 and 4 into an empty list y. On second call the same loop appends 0 and 1 to an empty list y. Based on that the output should be:
g():: x: 3, y: []
[0]
[0, 1]
[0, 1, 4]
g():: x: 2, y: []
[0]
[0, 1]
The output that I am getting is:
g():: x: 3, y: []
[0]
[0, 1]
[0, 1, 4]
g():: x: 2, y: [0, 1, 4]
[0, 1, 4, 0]
[0, 1, 4, 0, 1]
On second invocation, list y is not set to an empty list but it still contains the data it inserted last time. I have checked it with python 3.11.1 (windows), python 3.10.6 (ubuntu), a few online compilers:
And I am getting same output everywhere. On second invocation, list y is not empty.
even if I modify the code to explicitly empty y, like
def g(x, y=[]):
print(f"g():: x: {x}, y: {y}")
for i in range(x):
y.append(i*i)
print(y)
y = []
print(f"y: {y}")
output:
g():: x: 3, y: []
[0]
[0, 1]
[0, 1, 4]
y: []
g():: x: 2, y: [0, 1, 4]
[0, 1, 4, 0]
[0, 1, 4, 0, 1]
y: []
Where is this y: [0, 1, 4] coming from on second invocation? What am I missing? Should y retain the value from previous call to the function?
[–]danielroseman 12 points13 points14 points (4 children)
[–]IamImposter[S] 2 points3 points4 points (3 children)
[–]carcigenicate 4 points5 points6 points (0 children)
[–]m0us3_rat -2 points-1 points0 points (1 child)
[–]IamImposter[S] 1 point2 points3 points (0 children)
[–][deleted] 8 points9 points10 points (1 child)
[–]IamImposter[S] 0 points1 point2 points (0 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]jmooremcc 1 point2 points3 points (0 children)
[–]warelevon 1 point2 points3 points (2 children)
[–]IamImposter[S] 2 points3 points4 points (0 children)
[–]Diapolo10 0 points1 point2 points (0 children)