Lists, Arrays or Deques?
Compare Python list, collections.deque and doubly linked lists across real workloads, measure front-pop costs, and build an O(1) LRU cache from dict plus a doubly linked list.
Contentsand lesson path
On this page
- Why it matters
- Comparing list, collections.deque and doubly linked lists
- Where linked lists win: dict + doubly linked list for an LRU cache
- Check your understanding
- Apply it
- Review prompt
Lessons of Linked Lists
- Nodes, References and Sentinels Concept · 20 min
- Lab: A Doubly Linked List with a Sentinel Lab · 30 min
- Reference Surgery: Reverse, Merge, Split Worked example · 25 min
- Two Speeds Through One List Worked example · 20 min
- Lists, Arrays or Deques? Concept · 15 min
- Check: Linked List Exercises Knowledge check · 8 questions
What you will learn
- Compare linked lists with dynamic arrays and collections.deque for a given access pattern and justify the choice.
Prerequisites: Complexity Analysis
01. Why it matters
Many learners finish a first data-structures chapter thinking "arrays are fixed-size and slow to modify, while linked lists handle dynamic changes better". In Python, that intuition gets almost every everyday decision backwards: CPython list is already a dynamic array implemented in C with contiguous, CPU-cache-friendly pointers, whereas a pure-Python linked list allocates a separate heap object for every item and runs Python bytecode on every .next hop.
To pick the right sequence structure, you must match your workload's exact operation mix—random indexing, ends-only pushes and pops, sequential scans, or O(1) removal next to a known node handle—against each structure's memory layout. Below we compare Python list, collections.deque, and a doubly linked list side by side, measure front-pop timings, and build an O(1) LRU cache where a doubly linked list genuinely wins.
02. Comparing list, collections.deque and doubly linked lists
Look at how the three Python sequence structures store references in memory:
- Python
list(contiguous pointer array):O(1)random access (a[i]),O(1)amortisedappend/popat the right end, fast C sequential iteration, and compact per-slot storage (8 bytes per pointer on 64-bit, plus modest resize slack). Because pointers sit consecutively, CPU cache prefetching streams through elements cleanly, whereas chasing.nextacross scattered heap-allocatedNodeobjects misses CPU caches on every hop.listpaysO(n - i)pointer shifts oninsert(i, x)orpop(i), making repeatedpop(0)quadratic (O(n^2)overall). collections.deque(doubly linked list of fixed-size array blocks): built in C specifically for double-ended queues (O(1)append,appendleft,pop,popleft). Packing multiple pointers into each block cuts heap allocations and keeps C loops fast—while indexing near the middle (d[len(d) // 2]) must walk block-by-block from the nearer end inO(n)time. Passingmaxlen=kcreates a bounded ring that automatically discards the oldest item from the opposite end inO(1)when full.- Doubly linked list with sentinels:
O(n)random indexing and much higher memory per item thanlist(measured on 64-bit CPython 3.12.13 withtracemallocover 100,000 nodes holding small pre-internedintvalues and no__dict__access, our plain@dataclassDNodeaverages88bytes per node—sys.getsizeofreports48bytes for the base object before inline attribute storage, and touchingnode.__dict__makes CPython build a real dict on top, whichsys.getsizeofreports as roughly 100–300 bytes depending on interpreter state—while@dataclass(slots=True)reduces it to56bytes per node, against8bytes per pointer slot in alist), except when your code already holds a direct handle to nodexand must unlink or promotexin strictO(1)time without shifting neighbours—for example, promoting or evicting an entry in an LRU cache or cancelling a scheduled timer node.
Simplification note: our LRUCache stores integer keys and values inside @dataclass(eq=False) nodes; Python's standard collections.OrderedDict implements an internal C doubly linked dict table to avoid per-node Python object overhead.
Operation list collections.deque Doubly linked list
------------------------------------------------------------------------------------
Index at ends [0], [-1] O(1) O(1) O(1) (via sentinel)
Index middle [n // 2] O(1) O(n) (walks blocks) O(n) (walks nodes)
Append / pop right O(1) amort O(1) O(1)
Append / pop left O(n) O(1) O(1)
Unlink known node x O(n) shift O(n) (no node handle) O(1)from collections import deque
from dataclasses import dataclass
import timeit
@dataclass(eq=False)
class DNode:
val: int
prev: "DNode | None" = None
next: "DNode | None" = None
class Ring:
def __init__(self) -> None:
self.head = DNode(0)
self.head.prev = self.head.next = self.head
self.size = 0
def append(self, val: int) -> None:
assert self.head.prev is not None
tail = self.head.prev
node = DNode(val, prev=tail, next=self.head)
tail.next = self.head.prev = node
self.size += 1
def pop_front(self) -> None:
assert self.head.next is not None and self.head.next.next is not None
first = self.head.next
self.head.next = first.next
first.next.prev = self.head
self.size -= 1
def build_ring(n: int) -> Ring:
r = Ring()
for i in range(n):
r.append(i)
return r
n = 20_000
t_list = min(
timeit.repeat(
"while a: a.pop(0)",
setup=f"a = list(range({n}))",
repeat=5,
number=1,
)
)
t_deque = min(
timeit.repeat(
"while d: d.popleft()",
setup=f"from collections import deque; d = deque(range({n}))",
repeat=5,
number=1,
)
)
t_ring = min(
timeit.repeat(
"while r.size: r.pop_front()",
setup=f"from __main__ import build_ring; r = build_ring({n})",
repeat=5,
number=1,
)
)
print(f"n={n} front pops -> list.pop(0): {t_list*1000:.2f} ms")
print(f"n={n} front pops -> deque.popleft(): {t_deque*1000:.2f} ms")
print(f"n={n} front pops -> Python Ring.pop_front(): {t_ring*1000:.2f} ms")n=20000 front pops -> list.pop(0): 50.84 ms
n=20000 front pops -> deque.popleft(): 0.65 ms
n=20000 front pops -> Python Ring.pop_front(): 6.94 ms03. Where linked lists win: dict + doubly linked list for an LRU cache
Look at why deque.popleft() beat Ring.pop_front() in the benchmark above even though both are O(1): collections.deque packs pointers into C array blocks and runs C code without creating 20,000 Python node instances. So when do you write your own doubly linked list? When you need O(1) removal or promotion of an interior item given a handle, which neither list nor deque provides!
An LRU (Least Recently Used) cache illustrates this exact sweet spot. Every get(key) and put(key, value) must find an entry by key in O(1) (impossible in a linked list alone) and move that interior entry to the most-recent front or evict the oldest tail entry in O(1) (impossible in a plain list because middle deletion shifts O(n)). Pairing a dict[int, LRUNode] from Lab: Build a Chained Hash Map with a sentinel doubly linked list solves both halves in O(1). Notice that LRUNode stores both key and val: when evicting self.tail.prev at full capacity, del self.nodes[lru.key] needs lru.key directly so it never scans the dictionary.
from collections import deque
from dataclasses import dataclass
@dataclass(eq=False)
class LRUNode:
key: int
val: int
prev: "LRUNode | None" = None
next: "LRUNode | None" = None
class LRUCache:
def __init__(self, capacity: int) -> None:
if capacity < 1:
raise ValueError("capacity must be >= 1")
self.capacity = capacity
self.nodes: dict[int, LRUNode] = {}
self.head, self.tail = LRUNode(0, 0), LRUNode(0, 0)
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, node: LRUNode) -> None:
assert node.prev is not None and node.next is not None
node.prev.next = node.next
node.next.prev = node.prev
def _insert_front(self, node: LRUNode) -> None:
assert self.head.next is not None
first = self.head.next
node.prev, node.next = self.head, first
self.head.next, first.prev = node, node
def get(self, key: int) -> int:
node = self.nodes.get(key)
if node is None:
return -1
self._remove(node)
self._insert_front(node)
return node.val
def put(self, key: int, value: int) -> None:
existing = self.nodes.get(key)
if existing is not None:
existing.val = value
self._remove(existing)
self._insert_front(existing)
return
if len(self.nodes) == self.capacity:
assert self.tail.prev is not None and self.tail.prev is not self.head
lru = self.tail.prev
self._remove(lru)
del self.nodes[lru.key]
fresh = LRUNode(key, value)
self.nodes[key] = fresh
self._insert_front(fresh)
cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
print("get(1):", cache.get(1))
cache.put(3, 30)
print("get(2) after evict:", cache.get(2), "| get(3):", cache.get(3))
cache.put(3, 33)
print("get(3) after update:", cache.get(3), "| size:", len(cache.nodes))
dq = deque([10, 20, 30, 40])
dq.appendleft(5)
print("deque popleft:", dq.popleft(), "| middle read:", dq[len(dq) // 2])get(1): 10
get(2) after evict: -1 | get(3): 30
get(3) after update: 33 | size: 2
deque popleft: 5 | middle read: 30Trace the LRUCache operations above at capacity = 2. Calling put(1, 10) and put(2, 20) puts 2 at head.next and leaves 1 at tail.prev. Next, get(1) promotes 1 to head.next, leaving 2 as tail.prev. Then put(3, 30) sees len(self.nodes) == 2 == self.capacity, evicts tail.prev (key 2), and inserts 3 at the front. Finally, put(3, 33) finds existing first—updating 3 in place and keeping size == 2 instead of evicting anything.
Look closely at why put(key, value) checks existing = self.nodes.get(key) before checking if len(self.nodes) == self.capacity:. Suppose you reversed those two checks at capacity = 2 and ran put(1, 10), put(2, 20), and then put(2, 22): because len(self.nodes) == 2, the eviction check would fire before noticing that 2 already exists, wrongly evicting key 1 so get(1) returns -1! Checking existing first guarantees that key updates never trigger eviction, while capacity >= 1 ensures self.tail.prev is always a real node when len(self.nodes) == self.capacity.
When NOT to write a linked list: avoid custom Python linked lists in everyday code whenever a built-in C structure fits:
- Random index reads (
seq[i]): chooselist(O(1)vsO(n)), because array offset arithmetic beats walking node or block pointers. - Pure stacks or double-ended queues: choose
listfor stack-only orcollections.dequefor double-ended operations—both run in C without per-node object overhead. - Sorting or repeated full scans:
list.sort()(Timsort in C) and tight sequential loops run directly over contiguous pointers. - Deletion by value or index without handles: without a
dictor caller-heldNodereference, a doubly linked list still searchesO(n)before unlinking.
04. Check your understanding
05. Apply it
Complete the skill practice brief: put LRUCache in your own module and test it with Hypothesis against collections.OrderedDict (move_to_end and popitem(last=False)) over 2,000 random get/put operations at capacity = 1 and capacity = 3, verifying eviction order, updating existing keys without premature eviction, and missing-key returns.
From here, carry these reference and sequence trade-offs into Stacks, Queues & Deques, Recursion & Divide and Conquer, and Binary Trees & Traversals.
06. Review prompt
Without looking back:
- Compare
list,collections.deque, and a sentinel doubly linked list onpop(0)/popleft(), middle indexing[n // 2], and unlinking an interior node by handle. - Why did
collections.dequebeat our pure-PythonRingon 20,000 front pops even though both areO(1)? - Why does an
O(1)LRUCacherequire both adictand a doubly linked list—and why mustLRUNodestorekey?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.