Linked Lists in Python: Nodes, Pointers and Their Costs
A linked list is the opposite trade to an array. An array keeps its items side by side, so it can jump to any index at once but must shift items to insert in the middle. A linked list scatters its items across memory and chains them with pointers, so it can splice in a new item cheaply but must walk the chain to reach position i. Examples use Python 3.10 or later and only the standard library.
Nodes and pointers
Each item lives in a node, a small object holding the value and a reference to the next node. The list itself only needs to remember the first node, the head. The last node's next is None, which marks the end. To visit every item you start at the head and follow next until you reach None.
In a singly linked list each node points only forward. In a doubly linked list each node also has a prev reference to the node before it. That costs one more reference per node, but it lets you walk backward and, more importantly, delete a node you already hold in O(1), because you can reach its predecessor directly instead of searching for it.
A singly linked list in Python
This version keeps a tail reference as well as the head, so appending does not need to walk the whole list:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def push_front(self, value): # O(1)
self.head = Node(value, self.head)
if self.tail is None:
self.tail = self.head
def append(self, value): # O(1) thanks to the tail pointer
node = Node(value)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def find(self, value): # O(n): walk from the head
node = self.head
while node is not None:
if node.value == value:
return node
node = node.next
return None
def delete(self, value): # O(n) to find, O(1) to unlink
prev, node = None, self.head
while node is not None and node.value != value:
prev, node = node, node.next
if node is None:
return False
if prev is None:
self.head = node.next
else:
prev.next = node.next
if node is self.tail:
self.tail = prev
return True
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
items = LinkedList()
for x in [20, 30, 40]:
items.append(x)
items.push_front(10)
print(list(items))
print(items.find(30).value, items.find(99))
items.delete(10)
items.delete(40)
print(list(items), "tail =", items.tail.value)
[10, 20, 30, 40]
30 None
[20, 30] tail = 30
The method comments give the costs. push_front and append only rewire a couple of references, so they are O(1). find has to walk from the head, O(n) in the worst case. delete by value is O(n) because it must find the node and its predecessor first; the unlinking itself is O(1). Notice the bookkeeping in delete: removing the head and removing the tail are separate cases, and forgetting to update tail when the last node goes is a classic bug.
What each operation costs
| Operation | Singly linked list | Dynamic array (Python list) |
|---|---|---|
| Access item i | O(i), walk from the head | O(1) |
| Insert or delete at the front | O(1) | O(n) |
| Append at the end | O(1) with a tail pointer, O(n) without | Amortized O(1) |
| Delete the last item | O(n) singly (find the new tail), O(1) doubly | O(1) |
| Insert after a node you hold | O(1) | O(n) shift |
| Find by value | O(n) | O(n) |
The phrase "O(1) insert" for linked lists always carries a condition: you must already hold the node where the change happens. If you first have to find that node by position or value, the search costs O(n) and dominates.
Reversing a list and finding the middle
Two short pointer exercises show how linked-list code is usually written. Reversing in place walks the list once and turns each next pointer around, keeping three references: the reversed part so far (prev), the current node, and the rest of the list (nxt). It runs in O(n) time and O(1) extra space.
Finding the middle without knowing the length uses a fast and slow pointer: the slow pointer moves one node per step and the fast pointer two, so when the fast pointer reaches the end, the slow one is halfway. The same idea detects a cycle (if the fast pointer ever meets the slow one, the list loops). It is one of the patterns in two pointers and sliding window.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
def reverse(head):
prev = None
while head is not None:
nxt = head.next # remember the rest of the list
head.next = prev # point this node backward
prev, head = head, nxt
return prev
def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next # one step
fast = fast.next.next # two steps
return slow.value
print(to_list(reverse(build([1, 2, 3, 4, 5]))))
print(middle(build([1, 2, 3, 4, 5])), middle(build([1, 2, 3, 4, 5, 6])))
[5, 4, 3, 2, 1]
3 4
For a list of even length this version returns the second of the two middle nodes (4 out of 1 to 6). Changing the loop condition to fast.next is not None and fast.next.next is not None returns the first one instead; decide which you need and test both lengths.
Arrays versus linked lists
On paper the linked list wins for frequent insertion and deletion. In practice, arrays are faster for most workloads, and the reason is memory layout. An array's items sit next to each other, so reading one item pulls its neighbors into the processor's cache, and a scan through the array mostly reads fast memory. A linked list's nodes can be anywhere, so each step of a traversal may fetch from slow main memory. Each node also carries at least one extra reference, so the list uses more memory for the same data.
Linked lists earn their place when you hold references to nodes and need to splice them in and out in O(1): for example a doubly linked list paired with a dictionary from keys to nodes, a common way to build a least-recently-used cache, or a free list of reusable slots. They are also the natural shape for persistent data structures, where several lists share a common tail.
Linked lists in Python
Python has no built-in linked list class, and you rarely need to write one outside of learning and interview practice. When the real need is fast work at both ends, use collections.deque, which supports O(1) appends and pops on either side:
from collections import deque
d = deque([2, 3])
d.appendleft(1) # O(1) at the left end
d.append(4) # O(1) at the right end
print(d)
print(d.popleft(), d.pop()) # O(1) at both ends
print(d)
deque([1, 2, 3, 4])
1 4
deque([2, 3])
A deque is the standard choice for queues, as shown in stacks and queues. Indexing into the middle of a deque is O(n) near the center, so for random access by position a plain list is still the better tool; the arrays and dynamic arrays post lists its costs.
Check yourself
- Why does
appendbecome O(n) if you drop thetailreference? (You must walk from the head to find the last node.) - In a singly linked list, why is deleting the last node O(n) even with a tail pointer? (The new tail is the node before it, and the only way to find that node is to walk from the head.)
- What happens in
reverseif you assignhead.next = prevbefore savinghead.next? (You lose the rest of the list.)