+ 4

Python: why did the y.append(x) value of object a become the argument for object c?

def test(x,y=[]): print("======================") print("x = "+ str(x)) print("y = "+ str(y)) y.append(x) print("y.append(x) = "+ str(y)) return y a=test(111) print("a = "+ str(a)) b=test(2, []) # TWO arguments... print("b = "+ str(b)) # outputs b = [2] --> does this list have a 'none' or something? c=test(3) print("c = "+ str(c)) # how come the value 111 is suddenly passed to parameter y=[]? Why did the y.append(x) value of object a become the argument/parameter for object c?

18th Sep 2020, 11:21 PM
Solus
Solus - avatar
2 odpowiedzi
0
Function 'test' uses a cached `list` object when it is called without specifying an argument for parameter <y>. So the `list` object that is returned on the first and third call are the same one. Try to check their IDs and you'll see they both refer to the same `list` object 👇 print(id(a), id(c))
19th Sep 2020, 2:21 AM
Ipang
- 2
can you paste your outputs
19th Sep 2020, 1:26 AM
Jacob
Jacob - avatar