Follow the next pointer.
Understand node-based sequences and why constant-time local edits have conditions.
01 The idea
A singly linked list stores nodes that each point to the next node. It does not provide efficient arbitrary indexed access: reaching position k requires following links. Inserting after a known node is constant time, but finding that node may take linear time. Implementing this structure is a useful exercise even though Python’s built-in list is usually a more practical default.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from dataclasses import dataclass
@dataclass
class Node:
value: str
next: "Node | None" = None
head = Node("Build", Node("Test"))
head.next = Node("Review", head.next)
current = head
while current is not None:
print(current.value)
current = current.nextBuild Review Test
03 Under the hood
- 1
head names the first node. Each next reference represents one edge in the chain, and None marks the end.
- 2
The insertion preserves the old next reference by passing it to the new node before assigning head.next. Losing that reference would disconnect the rest of the list.
- 3
Memory overhead, locality, and pointer traversal matter in real implementations. The attractive complexity of one local operation does not make linked lists universally faster.
04 Your turn, builder
Write a function that counts nodes without converting the list into a Python list.
Reveal one possible solution +
from dataclasses import dataclass
@dataclass
class Node:
value: int
next: "Node | None" = None
head = Node(1, Node(2, Node(3)))
count, current = 0, head
while current is not None:
count += 1
current = current.next
print(count)05 Check your signal
Is finding the kth node constant time?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.