A singly linked list has only one pointer between two successive nodes, so it can only be traversed in a single direction — from the first node to the last, never the other way round.
class Node: def __init__(self, data=None): self.data = data self.next = None
n1 = Node('eggs')n2 = Node('ham')n3 = Node('spam')
n1.next = n2n2.next = n3To traverse the list:
current = n1while current: print(current.data) current = current.nextEach iteration prints the current element, then advances current to the next one, until the end
of the list is reached. Simple, but a raw node chain like this isn’t a good abstraction on its own.
Singly Linked List Class
A list is a separate concept from a node, so it gets its own class. Start with a constructor
holding a reference to the first node — since the list starts empty, that reference starts as
None:
class SinglyLinkedList: def __init__(self): self.tail = None