Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 59 / 101

Follow the next pointer.

Understand node-based sequences and why constant-time local edits have conditions.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

linked_lists.py
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.next
↳ EXPECTED OUTPUT
Build
Review
Test

03 Under the hood

  1. 1

    head names the first node. Each next reference represents one edge in the chain, and None marks the end.

  2. 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. 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

A SMALL MISSION

Write a function that counts nodes without converting the list into a Python list.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

Is finding the kth node constant time?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.