Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
What you will learn
- Describe a node as a data part plus an address part
- Add at the front of a linked list with two pointer moves
- Insert and remove a node by changing next, in the safe order
- Explain why get(i) is a walk of i hops
Before you start
- Python classes
- Arrays and dynamic arrays
In a linked list, every node has two parts: a data part and an address part, and the address part points to the next node. Changing the links is quick, but finding item number i means a walk.
Emma's treasure hunt
Emma is making a treasure hunt app for Jack's party. The hunt has three clues: Garden, Shed and Treasure. Jack holds the first clue, and each clue says only where the next one is. The garden clue says go to the shed, and the shed clue says look in the box, where the treasure is.
The app has two jobs. One: put a new clue first, the Kitchen. Two: read the fourth clue. Both should stay quick, even with a hundred thousand clues.
Adding a first clue is easy. Emma writes a kitchen clue that says go to the garden, and hands it to Jack. Two moves, and no other clue changes. But where's the treasure? There's no shortcut. Jack has to start at the first clue and follow them, one hop at a time.
A node: data and address
class Node:
def __init__(self, value):
self.value = value # the clue
self.next = None # where the next clue is
value is the data part, the clue itself. next is the address part: where the next node lives in memory. It starts as None, because nothing comes after it yet.
Where do the nodes sit in memory? Anywhere. They aren't side by side, and they aren't even in chain order. You find them by following the addresses. Python keeps the real addresses hidden, so the pictures here use small made-up ones like 380.
The chain
from node import Node
class ClueChain:
def __init__(self):
self.head = None # the first clue
self.hops = 0 # +1 for every n = n.next
def add_first(self, clue):
clue_node = Node(clue)
clue_node.next = self.head # 1. point at the old first
self.head = clue_node # 2. head points at the new
def get(self, i):
n = self.head
for k in range(i):
n = n.next
self.hops += 1
return n.value
def __str__(self):
s = "head"
n = self.head
while n is not None:
s += " -> " + n.value
n = n.next
return s + " -> None"
head holds the address of the very first node, and the chain knows nothing else. There are no index numbers anywhere. To reach a node, you follow next from head.
add_first: two address moves
from clue_chain import ClueChain
hunt = ClueChain()
hunt.add_first("Treasure")
hunt.add_first("Shed")
hunt.add_first("Garden")
print(hunt)
hunt.add_first("Kitchen")
print(hunt)
clue = hunt.get(3)
print("get(3) = " + clue + ", hops = " + str(hunt.hops))
head -> Garden -> Shed -> Treasure -> None
head -> Kitchen -> Garden -> Shed -> Treasure -> None
get(3) = Treasure, hops = 3
Each add_first goes in front, so Treasure, then Shed, then Garden leaves Garden first. Watch the addresses. Treasure gets a node at 100; move one copies head (None) into its next, and move two sets head to 100. Shed at 240 copies 100 into its next, so it points at Treasure, and head becomes 240. Treasure didn't move at all. Kitchen at 520 copies 380 from head, so it points at Garden, and head becomes 520.
A pointer move is nothing but copying an address. Two moves, whatever the size of the chain.
get(3): follow the addresses
The nodes have no numbers inside; positions 0 to 3 exist only for you. n = self.head gives 520, Kitchen. Then n = n.next runs three times: Kitchen's address part says 380 (Garden, hop one), Garden says 240 (Shed, hop two), Shed says 100 (Treasure, hop three). The loop ends and you get Treasure after three hops.
Compare that with an array, whose items sit side by side, so a[3] is one jump. A chain has nothing to calculate with. The only way is to follow.
Change the links
Since the links are just addresses, you can change them. relink_app.py builds three nodes by hand, slips one in, then takes one out:
from node import Node
def print_chain(head):
s = "head"
n = head
while n is not None:
s += " -> " + n.value
n = n.next
print(s + " -> None")
garden = Node("Garden")
shed = Node("Shed")
treasure = Node("Treasure")
garden.next = shed # link by hand
shed.next = treasure
print_chain(garden)
pond = Node("Pond")
pond.next = garden.next # 1. Pond points at Shed
garden.next = pond # 2. Garden points at Pond
print_chain(garden)
pond.next = pond.next.next # skip Shed: it is removed
print_chain(garden)
head -> Garden -> Shed -> Treasure -> None
head -> Garden -> Pond -> Shed -> Treasure -> None
head -> Garden -> Pond -> Treasure -> None
To slip Pond in, move one copies Garden's next into Pond, so Pond points at Shed. Move two points Garden at Pond. Do them in that order. If you change Garden first, nobody holds Shed's address any more, and Shed and Treasure are lost.
To remove Shed, pond.next = pond.next.next copies Shed's next (Treasure) into Pond. One address change, and the chain jumps straight over Shed. Nothing points at Shed now, so the walk never reaches it, and Python cleans it up later. No node moved in memory; only the address parts changed.
Grow the chain
from clue_chain import ClueChain
for n in (1_000, 10_000, 100_000):
chain = ClueChain()
for i in range(n):
chain.add_first("clue " + str(i))
chain.hops = 0
chain.add_first("new start")
add = chain.hops
chain.hops = 0
chain.get(n) # the very last clue
walk = chain.hops
print(f"{n:7,d} clues: addFirst {add} hops, "
f"get(last) {walk:7,d} hops")
1,000 clues: addFirst 0 hops, get(last) 1,000 hops
10,000 clues: addFirst 0 hops, get(last) 10,000 hops
100,000 clues: addFirst 0 hops, get(last) 100,000 hops
Adding a new first clue takes zero hops at every size, because only head and the new node are involved. Reading the last clue walks past every clue on the way.
Read the cost off the code
| Operation | Linked list | Array |
|---|---|---|
| Add at the front | O(1), two moves | O(n), every item shifts |
| Insert or remove after a node you hold | O(1), change one or two addresses | O(n) |
| Get item i | O(n), i hops | O(1), one jump |
A chain is great at changing and slow at finding. An array is the other way round. And going back one node? A node knows only the next one. If each node also remembered the one before it, you'd have a doubly linked list, at the price of one extra address per node.
Where you meet a linked list
Hash tables chain together two keys that land in the same bucket. A cache that forgets the oldest item keeps its items in a two-way chain and moves the one you used last to the front. Operating systems keep free pieces of memory in a chain. And a queue of jobs adds at the back and takes from the front, which a chain does cheaply; queues covers that.
Recap
- A node has a data part and an address part,
next. add_firstis two address moves, O(1). Insert and remove are just changingnext, in the safe order.get(i)walks i hops, so it's O(n).
Try it yourself: in relink_app.py, put a new node between Pond and Treasure, and predict the printed chain before you run it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
Queues: First In, First Out, With a Ring of Cells
A queue is first in, first out: whoever joins the line first is served first. Build Kate's cinema ticket line in Python as a ring of four cells, where nobody steps forward and only head and tail move, serve a million people with the same four cells, then break it with a line that is already full.
