When you call 'append' with a list, the pointer of the list is passed in, so the original data is changed.
>>> tmp = [1,2]
>>> tmp.append(3)
>>> tmp
[1, 2, 3]
Here comes my question. For the following code, when I pass the Node object named 'head' into the method 'get', I expect that head would point to the second node with value 2 after calling the method. However, it turns out that 'head' is still pointing to the first node with value 1.
>>> class Node:
def __init__(self, val):
self.val = val
self.next = None
def get(self, index):
for i in range(index):
self = self.next
return self.val
>>> head = Node(1)
>>> head.next = Node(2)
>>> head.get(1)
2
>>> head.val
1
Can anyone explain why is this happening? To my understanding, as Node is mutable, a reference should be passed in. How can I know whether a reference or value is passed in? Thanks in advance!