0

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)
mgus
  • 768
  • 3
  • 14
  • 31
  • All you are doing is taking the name `head` which was referring to `n1` and pointing that name at `n2` this doesn't effect the objects `n1` or `n2` at all. – Mark Jan 30 '20 at 04:15
  • @MarkMeyer I still don't understand. I can replicate this behavior even if I execute the same code in the main function and use `n1` instead of `head` and `n1backup` instead of `headCpy`, please see edits. – mgus Jan 30 '20 at 04:25
  • `headCpy = head` does not make a copy of the node; it just makes another reference to the same node. Read https://nedbatchelder.com/text/names.html for more discussion about how Python names work. After you write `head = head.next`, `headCpy` still refers to the node that `head` used to refer to. – chepner Jan 30 '20 at 04:32

0 Answers0