Search code examples
pythonclasslinked-listself

How does self.next = None store the address of next value in the linked list?


I am new to classes in Python. I am trying to implement linked lists. Can someone please explain to me how self.head.next.value outputs the next value in the list? Even though next is assigned to none but somehow it is able to print the right answer. I saw a similar post here How does self.next = None get the next value of l1? but the answer was not properly explained since I am not assigning anything to self.next.

class Element(object):
    def __init__(self, value):
          self.value = value
          self.next = None

class LinkedList(object):
    def __init__(self, head=None):
        self.head = head

    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element

l = LinkedList(Element(1))
l.append(Element(2))
print (l.head.next.value)

The output shows : 2


Solution

  • [...] since I am not assigning anything to self.next.

    Well, you initialize .next to None. Howeever, when you call append(), that changes the last element's .next:

    current.next = new_element