Reputation: 73
I have a question about how mutation works in linked lists with binding assignment.
Suppose we have the following linked list data type in python:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
Suppose we have an object a
and bind curr
to a
:
a = ListNode(1, ListNode(2))
curr = a
Both are 1 -> 2 ->. Now if I try to mutate curr
:
curr.next = ListNode(3)
curr = curr.next
Now a
is 1 -> 3 -> while curr
is 3 ->.
Here comes the part where I get confused. If I keep updating curr
by:
curr.next = ListNode(4)
curr = curr.next
Now a
is 1 -> 3 -> 4 -> while curr
is 4 ->.
I'm wondering why would a
be updated in this way?
Upvotes: 1
Views: 88
Reputation: 10865
Because after
curr = a
, curr
and a
are the same object.
And then, after
curr = curr.next
, curr
and a.next
are the same object, which you can see by looking at the IDs (or even better, by going retro and drawing boxes and arrows with pen and paper :)
In [8]: id(curr)
Out[8]: 4509135032
In [9]: id(a.next)
Out[9]: 4509135032
Hence when you then modify curr.next
, you are also modifying a.next.next
.
Upvotes: 2