Sub topic 6
Linked lists versus arrays: costs and trade-offs
This chapter assumes you can read the Node and LinkedList classes from the earlier chapters, that you know introductory Big-O notation, and that you have used Python lists. Here we compare the two structures on time, memory, and real hardware behavior, then state when each one is the right choice.
Two ways to store a sequence
An array stores its elements in one contiguous block of memory. The address of element i is computed from the start address and the element size, so reading a[i] takes one step no matter how large the array is.
A linked list stores each element in its own node. The nodes can sit anywhere in memory, and each node holds a reference to the next one. To reach element i, you must follow i references from the head.
Python's built-in list is a dynamic array. It holds a contiguous block of references to objects and grows the block when it fills up. When this chapter says "array", it means that structure. When it says "linked list", it means the singly linked list you built earlier.
Cost of each operation
The table uses n for the number of elements. It assumes a singly linked list that stores only a head reference, as in the code you wrote earlier.
| Operation | Array (dynamic) | Singly linked list |
|---|---|---|
| Read element at index `i` | O(1) | O(i), up to O(n) |
| Search for a value | O(n) | O(n) |
| Insert at the front | O(n), every element shifts | O(1) |
| Insert at the back | O(1) amortized | O(n) with only a head, O(1) with a tail reference |
| Insert after a node you already hold | O(n), elements shift | O(1) |
| Delete at the front | O(n), elements shift | O(1) |
| Delete a node you already hold | O(n) | O(n) in a singly linked list, because you need its predecessor |
| Delete by value | O(n) | O(n) |
Three rows deserve explanation.
Index access. This is the array's main advantage. The linked list has no way to jump to position i. Code like the following hides a loop:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def get_at(head, index):
current = head
for _ in range(index):
if current is None:
raise IndexError("index out of range")
current = current.next
if current is None:
raise IndexError("index out of range")
return current.value
head = Node(10, Node(20, Node(30)))
print(get_at(head, 2)) # 30Calling get_at inside a loop over every index costs O(n²) in total, where an array would cost O(n).
Insertion at the front. Inserting at index 0 of an array moves every element one slot to the right. Inserting at the head of a linked list creates one node and changes one reference.
"Insert after a node you already hold." The O(1) claim for linked lists depends on already having the node. Finding that node usually costs O(n). Linked lists are fast at the splice itself, not at locating the splice point. This distinction is the most common source of wrong conclusions in comparisons.
Measuring the difference
You can observe the front-insertion gap directly. The program below inserts at the front of each structure.
import time
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def time_array_front_inserts(n):
data = []
start = time.perf_counter()
for i in range(n):
data.insert(0, i)
return time.perf_counter() - start
def time_list_front_inserts(n):
head = None
start = time.perf_counter()
for i in range(n):
head = Node(i, head)
return time.perf_counter() - start
for n in (10_000, 20_000, 40_000):
a = time_array_front_inserts(n)
l = time_list_front_inserts(n)
print(f"n={n:>6} array={a:.4f}s linked list={l:.4f}s")Doubling n roughly quadruples the array time, because each insert is O(n) and there are n of them. The linked list time only doubles. Exact numbers depend on your machine.
The array version has an excellent constant factor, since list.insert uses a fast memory move. The quadratic growth still dominates once n is large.
Memory costs
A linked list spends extra memory on references. Each node stores the value and at least one reference. A doubly linked node stores two references.
In CPython the overhead is larger than in languages like C. Every Node instance is a Python object with a header and, by default, a per-instance dictionary for its attributes. A node can easily use several times the memory of one slot in a Python list. Declaring __slots__ removes the dictionary:
import sys
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class SlotNode:
__slots__ = ("value", "next")
def __init__(self, value, next=None):
self.value = value
self.next = next
plain = Node(1)
slotted = SlotNode(1)
print(sys.getsizeof(plain) + sys.getsizeof(plain.__dict__))
print(sys.getsizeof(slotted))The second number is smaller on any CPython version. The exact byte counts vary by version.
Arrays have their own overhead. A dynamic array keeps spare capacity so that appends are cheap, so part of its block is unused at any moment. A fixed-size array has no such waste, but you must know the size in advance.
Cache locality
Modern processors read memory in cache lines, which are blocks of typically 64 bytes. Reading one array element loads its neighbors into the cache too, so a scan over an array tends to find the next element already loaded. Linked list nodes are allocated separately, so following a reference often jumps to a distant address and misses the cache.
This is why a linked list scan is often slower in practice than an array scan, even though both are O(n). Big-O hides this constant factor. In low-level languages the gap can be large. In Python the effect is blurred, because a list holds references to objects that are themselves scattered in memory, so even array traversal chases pointers. The asymptotic conclusions still hold.
Amortized versus worst-case cost
A dynamic array appends in O(1) amortized time. Most appends write into spare capacity. Occasionally the array is full, and it allocates a larger block and copies every element, which costs O(n) for that one append.
A linked list insertion at a known position is O(1) every time, with no occasional spike. This matters when worst-case latency is important, for example in code that must respond within a fixed time limit. Averages hide the spike, but a real-time system feels it.
Common mistakes
- Treating "insert is O(1)" as unconditional. It is O(1) only when you already hold the node before the insertion point. Searching for it is O(n).
- Using a linked list for random access. If your code reads by index, use an array.
- Choosing a linked list because "arrays are slow to insert". For small
n, array shifting is fast, and the array's cache behavior often wins. Measure before choosing. - Forgetting that deleting a node from a singly linked list needs its predecessor. Without a
prevreference, you must walk from the head. A doubly linked list removes this cost, as a later chapter shows.
Choosing between them
Prefer an array when:
- You read elements by index often.
- You mostly append at the end and iterate.
- Memory use and scan speed matter.
- The collection is small.
Prefer a linked list when:
- You insert or delete often at the front, or at positions you already hold references to.
- You need constant-time worst-case insertion.
- You need to splice whole lists together or rearrange nodes without copying elements.
- Other code holds references to nodes and must stay valid after unrelated insertions. Array insertion shifts elements, so index positions change. Node references do not.
Summary of the trade-off
The two structures trade one strength for another. Arrays give instant access by position and fast scans, and they pay when elements must shift. Linked lists give cheap local changes and pay for slow access by position, extra memory per element, and poor cache behavior. The right choice follows from the access pattern of your program, so write down that pattern before picking a structure.
Exercise
A program keeps a playlist and often removes the song currently playing, for which it already holds the node, and inserts a new song right after it. It almost never reads songs by position. Would a singly linked list or an array suit it better, and what extra piece of information does a singly linked list need to delete the current song in O(1)?
Show answer
A linked list suits it better, because insertion after a held node is O(1) and the program never needs index access, so array shifting would be pure cost. To delete the current node in O(1), a singly linked list needs the predecessor node, since the predecessor's next must be redirected. Keeping a prev reference (a doubly linked list) provides it. Without it, finding the predecessor costs O(n).
Exercise
A loop calls get_at(head, i) for every i from 0 to n - 1 on a singly linked list of n nodes. What is the total running time, and how would you rewrite it to run in O(n)?
Show answer
The total is O(n²), because call i walks i references, and 0 + 1 + ... + (n - 1) is about n²/2. Rewrite it as one traversal that keeps a current reference and advances it once per iteration, doing the work for each node as you pass it.