Consider the following simple construction of a singly-linked list. Suppose that I want to keep a backup of the head and after doing something to the list return back to the head. I thought that I would need to do a copy()
or deepcopy()
to get a replica of the head before changing it (see also here and here). However, this does not seem to be the case here and I can do it with a simple assignment =
. I cannot explain this behavior and why it works. Can you provide any sources to help me understand it?
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Class:
def foo(self, head: ListNode):
headCpy = head
print(id(head))
print(head.val)
print(id(headCpy))
print(headCpy.val)
head = head.next
print(id(head))
print(head.val)
print(id(headCpy))
print(headCpy.val)
if __name__ == '__main__':
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
Class().foo(n1)
The following has the same issue
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
n1backup = n1
n1 = n1.next
print(n1backup.val)
print(n1.val)