4/39
Part 1 of 7 · Nodes and costsLearn

A pointer makes the front cheap, and costs the index

A linked list and a Python list trade costs. Here is each side of the trade, measured on Python 3.12 on an M1 Pro laptop.

def linked(vals):
    head = None
    for v in reversed(vals):
        head = Node(v, head)
    return head


print(values(linked([3, 1, 4, 1, 5])))
[3, 1, 4, 1, 5]

linked builds a list from the back, adding each value at the front with head = Node(v, head). Each add is one new node and one pointer. Nothing already in the list moves. The rest of this lesson builds its lists with linked.

A Python list keeps its items side by side in one block of memory. To make room at the front, it shifts every item one place, and the Python tutorial says that's why inserting at the front is slow:

xs.insert(0, 7) on a Python list
before
31415
after
731415

All 5 items, in green, moved one place to make room.

head = Node(7, head) on a linked list
before
3
→
1
→
4
→
1
→
5
→None
after
7head
→
3
→
1
→
4
→
1
→
5
→None

One new node and one new pointer. Nothing else moves.

Here is the cost of one insert at the front of n items, the median of 5 runs of 1,000 inserts:

nPython list, µslinked list, µsdeque, µs
1,0000.2260.0960.017
10,0001.6170.0960.017
100,00017.4930.0990.016
1,000,000194.3620.1010.017

The calls are xs.insert(0, x), head = Node(x, head) and dq.appendleft(x).

From 10,000 items up, ten times the items made the list's insert about ten times slower: O(n). The linked list didn't move: O(1).

And collections.deque, a double-ended queue written in C, was about six times faster again than the linked list built in Python.