Assigning a variable to an earlier ListNode variable

Viewed 23

I have code that works exactly how I want it to but I don't understand why Python is allowing for ListNode x.next to be changed when a separate ListNode y gets an update to its y.next value. see below code:

    class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
x = ListNode(1, None)
a = ListNode(2, None)
y = x
b = ListNode(5, None)

x.next = a
y.next = b

print(x.val)          >>>       1
print(x.next.val)     >>>       5        # how is this not 2 ???

This flies in the face of what I thought I knew about assigning multiple variables in Python. This seems to be the opposite of how Python handles multiple variables. Notice how in the below code, changing 'y' doesn't change what 'x' is:

x = 5
y = x

y += 1

print(y)      >>>    6
print(x)      >>>    5
1 Answers

x is an object so y=x means that y is that same object. likewise x.next = a means that x.next = ListNode(2, None) because a = ListNode(2, None)... and the same for b, this is why... in fact in the debugger you can see the memory space allocated to each.

Here is the debugger image to show this...

enter image description here

Related