h =[0][1][3][7][4]1parent = (i - 1) // 22left = 2 * i + 13right = 2 * i + 2[2][5][6][0]2[1]4[2]3[3]8[4]5[5]7[6]6[7]12345678
Pucks: the values; seats: the list indices laid out as a treeCells in front: the same list h, index by indexTwo pucks trading seats: one swap of a siftOne list, drawn twice: as a tree of seats (index 0 at the back) and as the row of cells h in front. Push appends at the end and swaps the new item up while it is smaller than its parent; pop takes h[0], moves the last item to the root and swaps it down with its smaller child. Each swap moves one level, so both cost O(log n).

A list that is a tree

  1. A binary heap is a plain Python list read as a tree. h[0] is the root. The item at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. No pointers are stored.

Push and sift up

Pop and sift down

Why it is fast

What happens

;; step 1/8 · list-as-tree
h = [2, 4, 3, 8, 5, 7, 6]

parent = (i - 1) // 2
left   = 2 * i + 1
right  = 2 * i + 2

i = 0: children 1, 2      (values 4, 3)
i = 1: children 3, 4      (values 8, 5)
i = 2: children 5, 6      (values 7, 6)
i = 6: parent (6 - 1) // 2 = 2

Python and MIT 6.006 count from index 0, so the children of i are 2i + 1 and 2i + 2. CLRS and Sedgewick and Wayne count from 1 and use 2i and 2i + 1, with the parent at i // 2. Same tree, shifted by one. heapq's heappop uses a faster variant of sift down: it moves the smaller child up all the way to a leaf, then sifts the item back up a little, which saves comparisons. On this example it gives exactly the same list.