Search code examples
pythonlinked-listvariable-assignmentfunction-call

Why does calling a function and writing statements explicitly work differently in Python?


I need an insert to head operation for a linked list that I implemented. However, doing this operation by function call (like insertToHead) and writing the statements explicitly where I need them produces different results. I wonder which property of Python leads to that difference but I couldn't figure it out.

To be more specific, let's say that I have the following class for the linked list:

class Node:
    value = None
    nextNode = None

    def __init__(self, value):
        self.value = value

    def insertToHead(self, value):
        newHead = Node(value)
        newHead.nextNode = self
        return newHead

For a linked list with a single element (say, 2) I want to insert a node (say, 0) to the head to make linked list 0 -> 2.

I created the linked list the following way

head = Node(2)

Then I tried to insert 0 to head two ways:

  1. Writing the statements explicitly where I need them
newHead = Node(0)
newHead.next = head
head = newHead

Now head is 0, not 0 -> 2.

  1. Calling insertToHead
head = head.insertToHead(0)

head is 0 -> 2 after this statement.

Does anyone know why these two approaches result in differently?


Solution

  • You have a typo. newHead.next should be newHead.nextNode.