A linked list stores items not side by side in memory but in nodes: each node carries the data and a reference to the next node. This simple idea makes insertion and deletion O(1) with no shifting, but turns index access into O(n). The memory model of an array was covered in array and dynamic array.
The node and the LinkedList class
Node stores two fields: value and next. The list knows only head and counts its size separately so that len is O(1). __iter__ is written as a generator (iteration protocol), so list(...), sum(...) and in work out of the box; see dunder methods for __len__.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self._size = 0
def push_front(self, value):
self.head = Node(value, self.head)
self._size += 1