Skip to the workspace
Pebellslearn by building
Data Structures in Practice  ›  Lesson

Arrays & Linked Lists

Arrays and Linked Lists 17 minAn array locates elements by index. A linked list connects nodes through references to the next or previous node.

An array locates elements by index. A linked list connects nodes through references to the next or previous node.

Compare updates and traversal, then reverse links without losing the unvisited part of a chain.

Indexing, prepending, and splicing are different operations even when they produce the same sequence. Compare a Python list's array of references with a chain of nodes, using the object relationships you already know. Then reverse a chain while preserving access to the unvisited nodes—the part that output-only examples tend to hide.

Top row: five numbered boxes side by side labelled 0,1,2,3,4, each reachable directly — "array: jump straight to index i". Below: five separate boxes connected by arrows, each pointing only to the next — "linked list: walk one link at a time to get anywhere"

Prepend a song to a playlist

A playlist app keeps the queue as a plain Python list — values[i] reaches any track instantly, which is exactly what a dynamic array is built for. The trouble starts the moment someone taps "play next" on a track that isn't at the front yet. Pushing it to position 0 feels like it should cost the same as adding a track at the end, but it doesn't:

What does this print?
values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
values.insert(0, 1)
print(values[5])

That's the mistake: treating insert(0, x) as a cheap operation because values[i] is cheap. They are not the same thing. Indexing jumps straight to a slot; inserting at the front has to physically move every item after it one slot over to make room, which gets slower the longer the playlist gets. append is amortised constant-time: most appends use spare capacity, while an occasional resize allocates a larger reference array and copies references. That asymmetry (cheap at the end, expensive at the front) is the whole reason collections.deque exists: it's built to make both ends cheap, which you'll meet properly in the next lesson.

Preparing this topic’s interactive investigation…

Walk a browser's back-button history

Model a simple history as links to adjacent visits. This is a teaching model, not a claim about how every browser implements history: a chain of separate Node objects, each holding a value and a pointer to whatever comes next, with None marking the end of the chain:

python

There's no history[2] — walking one .next at a time is the only way in. The mistake people make here is reaching for square brackets out of habit, because that's how every sequence has worked so far in Python:

broken — fix itTypeError

Run it and read the error. Then print the third node's value WITHOUT square brackets.

A Node has no __getitem__, so indexing simply isn't defined — Python raises TypeError rather than guessing. The payoff for giving up indexing: once you're already standing at a node (say, the "product" page), splicing a new page in next to it is a couple of pointer rewrites — no shifting anything else in the whole chain, which is exactly the opposite trade-off from the playlist above.

The identity lesson gives a precise way to read pointer rewrites: node.next is a reference stored on an object, while node = ... moves a local name. Before reversing a link, save the next node or the remaining chain becomes unreachable from your traversal.

For 1 → 2 → 3 → None, maintain two regions: previous heads the reversed prefix, and current heads the unvisited suffix.

Before an iteration Save Reverse one link Advance names
previous=None, current=1 following=2 1.next=None previous=1, current=2
previous=1, current=2 following=3 2.next=1 previous=2, current=3
previous=2, current=3 following=None 3.next=2 previous=3, current=None

At every boundary, those two regions contain all original nodes exactly once. The final previous is the new head. Writing current = current.next after reversing the link follows the new backward link, which loses your place. Use the table to implement the later reversal exercise without copying values.

Cost depends on what you already hold. Splicing after a known node takes a fixed number of reference changes; finding that node by position still takes a walk. A Python list stores a contiguous array of object references, not all element objects inline. Appends are amortised constant-time: an occasional resize copies references. A deque optimises the ends, not arbitrary interior splicing. Choose from the operations your program actually repeats.

Picking between the two

In real Python code, that choice almost always comes down to one question: do you need to jump to a position by index, or only ever walk forward from wherever you are? A playlist, a spreadsheet row, anything you address by position — use a list. A browser's back/forward history, an undo chain, anything you only ever step through one link at a time and need to splice mid-walk — a linked chain (or another structure designed for those operations) fits better. Python's own list quietly covers both jobs reasonably well for small data, which is exactly why this trade-off only starts to matter once a collection gets large or the front gets touched constantly.

Quick practice

What does this print?
class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

a = Node(1)
b = Node(2)
a.next = b
b.next = a
print(a.next.next.val)
What does this print?
values = [1, 2, 3, 4, 5]
print(values[2], values[-1])

🎯 Your turn

Write round_trip(values). Build a linked list from values using a Node class, then walk it back into a plain Python list and return that:

  • round_trip([1, 2, 3]) → [1, 2, 3]
  • round_trip([]) → []

Hint — build(values) links each new Node onto a running tail; to_list(head) walks node = node.next until it hits None, collecting .val as it goes.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below reverses a chain in place — no library, just pointers.

Your task
Write round_trip(values). Build a linked list from values using a Node class (val, next), then walk it back into a plain Python list and return that. Example: round_trip([1, 2, 3]) -> [1, 2, 3].

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upInsert at the front of an array

Write prepend(values, x) that inserts x at the very front of values and returns it.

arraysarray
DrillA two-node chain

Using a Node class with val and next, write two_node_values(a, b) that builds a two-node chain (a then b) and returns [head.val, head.next.val].

linked-listsnode
BuildSum a chain by walking it

Write chain_sum(values). Build a linked list from values, then walk it with a loop (not sum(values) directly) and return the total.

linked-lists
BossReverse a chain in place

Write reverse_chain(values). Build a linked list from values, reverse its pointers IN PLACE (the classic prev/curr walk — no list, no slicing), then return the reversed chain as a list.

linked-listsreverse-list
CapstoneFind the middle, fast and slow

Write middle_value(values). Build a linked list from values, then find the middle node's value using the fast/slow pointer technique: slow moves one step at a time, fast moves two, and when fast runs out, slow is at the middle. Return None for an empty list.

linked-listsfast-slow-pointers
Project context and further resources
round_trip.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
round_trip(values) → listBuild a linked list from values, then walk it back into a list.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.