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:
before after All 5 items, in green, moved one place to make room.
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:
| n | Python list, µs | linked list, µs | deque, µs |
|---|---|---|---|
| 1,000 | 0.226 | 0.096 | 0.017 |
| 10,000 | 1.617 | 0.096 | 0.017 |
| 100,000 | 17.493 | 0.099 | 0.016 |
| 1,000,000 | 194.362 | 0.101 | 0.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.