Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 15 min · revision 1

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

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) amortised append/pop at 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 .next across scattered heap-allocated Node objects misses CPU caches on every hop. list pays O(n - i) pointer shifts on insert(i, x) or pop(i), making repeated pop(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 in O(n) time. Passing maxlen=k creates a bounded ring that automatically discards the oldest item from the opposite end in O(1) when full.
  • Doubly linked list with sentinels: O(n) random indexing and much higher memory per item than list (measured on 64-bit CPython 3.12.13 with tracemalloc over 100,000 nodes holding small pre-interned int values and no __dict__ access, our plain @dataclass DNode averages 88 bytes per node—sys.getsizeof reports 48 bytes for the base object before inline attribute storage, and touching node.__dict__ makes CPython build a real dict on top, which sys.getsizeof reports as roughly 100–300 bytes depending on interpreter state—while @dataclass(slots=True) reduces it to 56 bytes per node, against 8 bytes per pointer slot in a list), except when your code already holds a direct handle to node x and must unlink or promote x in strict O(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.

Text · operation costs for list, collections.deque and doubly linked list
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)
Python · measuring 20,000 front pops across list, deque and pure-Python Ring
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")
Illustrative output (CPython 3.12.13 on Linux lab host; timings vary by CPU and load)
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 ms

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

Python · O(1) LRUCache combining dict and sentinel doubly linked list
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])
Expected output
get(1): 10
get(2) after evict: -1 | get(3): 30
get(3) after update: 33 | size: 2
deque popleft: 5 | middle read: 30

Trace 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]): choose list (O(1) vs O(n)), because array offset arithmetic beats walking node or block pointers.
  • Pure stacks or double-ended queues: choose list for stack-only or collections.deque for 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 dict or caller-held Node reference, a doubly linked list still searches O(n) before unlinking.

04. Check your understanding

Practice check · 3 questions

Matching structures and LRU mechanics

Evaluate memory layout trade-offs and LRUCache invariants.

Q1. Both `collections.deque.popleft()` and `Ring.pop_front()` run in `O(1)`, yet in our 20,000-pop benchmark `deque` ran far faster. Why?
Q2. In `LRUCache(capacity=1)`, you call `put(1, 10)`, then `put(1, 99)`, then `put(2, 20)`. What do `get(1)` and `get(2)` return?
Q3. In `LRUCache`, `self.nodes` already maps `key -> LRUNode`. Why must each `LRUNode` still store `self.key` alongside `self.val`?
Practice only: not graded, not saved, not evidence.

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:

  1. Compare list, collections.deque, and a sentinel doubly linked list on pop(0) / popleft(), middle indexing [n // 2], and unlinking an interior node by handle.
  2. Why did collections.deque beat our pure-Python Ring on 20,000 front pops even though both are O(1)?
  3. Why does an O(1) LRUCache require both a dict and a doubly linked list—and why must LRUNode store key?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check