Status of ''self.head'' in a singly link list


I’ve been practicing link list but can’t understand what ”self.head” actually refers.
Is it the first value in a list at index 0? And how can I print data inside the head?

class Node:
    def __init__(self, data=None, next=None): = data = next

class Linkedlist:
    def __init__(self):
        self.head = None
    def print_var(self):
        itr = self.head
def insert_at_begining(self, data):
    node = Node(data, self.head)
    self.head = node
if __name__ = '__main__':
ll = Linkedlsit()

If I’m to call print fuction function, it will through an error.
(Say, linklist is not empty)

Asked By: Aleef



self.head refers to the first Node in the list. From there, you can "walk" the list with something like:

current_node = ll.head
while current_node:
    print(f"Current node data: {}")
    current_node =

print("Reached End of List")
Answered By: Cargo23

Check out my code and related comments

ll = LinkedList() # Create empty list
print(ll.head) # This prints None, because the list is empty, there are no nodes
ll.print_var() # This gives you an error. You're trying to print, but as shown before ll.head is None, not a Node
ll.head = Node('hello', ll.head) # The list now has one node
ll.print_var() # This is now working, and prints 'hello'
Answered By: Riccardo Bucco

After fixing your misspellings and calling the function by its proper name, print_var, it functions as it should. If you wanted to display your entire linked list you can do so with one of these methods:

    def __iter__(self):
        node = self.head
        while node is not None:
            node =
        yield node

    def show(self):
        node = self.head
        while node is not None:
            print(, end=" -> ")
            node =

__iter__ makes it an iterable you can loop through and show() will print the contents of the linked list.

As for self.head, it points to the newest node added to your linked list or None in an empty linked list.

Answered By: Sculby
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.