Python ListNode object update in a linked list doesn't work as expected

21 Views Asked by At

Let's say we're trying to implement a linked list in Python, with each ListNode defined as following:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

And let's also say we have a simple linked list of 1 -> 2 -> 3 -> None, defined as following:

a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c

Now when I hold a variable pointing to c and update itself like this:

c = c.next

I expected that the linked list from a will look like: 1 -> 2 -> None because node c is updated. However, to my surprise, the linked list from a still keeps its original form: 1 -> 2 -> 3 -> None.

Why is this the case? Doesn't the variable c hold the actual reference to that ListNode object and the change to itself should therefore reflect when we see the entire list from node a?

1

There are 1 best solutions below

0
trincot On BEST ANSWER

Assignment to a name (variable) never mutates a data structure, like setting an attribute of an object.

Here is your linked list:

  a:┐             b:┐             c:┐
    │               │               │
┌───┴───────┐   ┌───┴───────┐   ┌───┴───────┐
│ val: 1    │   │ val: 2    │   │ val: 3    │
│ next: ────────┤ next: ────────┤ next: None│
└───────────┘   └───────────┘   └───────────┘

Once you assign c = c.next, you're taking the value of c.next -- which is None and assign it to the c name:

  a:┐             b:┐             c: None
    │               │                
┌───┴───────┐   ┌───┴───────┐   ┌───────────┐
│ val: 1    │   │ val: 2    │   │ val: 3    │
│ next: ────────┤ next: ────────┤ next: None│
└───────────┘   └───────────┘   └───────────┘

When you'd want that b.next becomes None, you'll really have to assign that to b.next. Note that b.next is an attribute that is distinct from the name c.