A list that is a tree
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.
The rule: every parent is less than or equal to its children. So the smallest item is always h[0]. The rest is only loosely ordered: [2, 4, 3, 8, 5, 7, 6] is a valid heap, but it is not sorted.
Push and sift up
heapq.heappush(h, 1) first appends 1 at the end, index 7. The tree stays complete: filled level by level, left to right. Its parent is at (7 − 1) // 2 = 3 and holds 8. 8 > 1 breaks the rule.
Sift up: while the new item is smaller than its parent, swap the two. 1 swaps with 8, then with 4, then with 2. Now it is the root, so it stops: 3 swaps, one per level.
Pop and sift down
heapq.heappop(h) returns h[0], the smallest item: 1. To keep the tree complete, the last item, 8 from index 7, moves into the root. The list is back to 7 items, but 8 on top breaks the rule.
Sift down: swap the item with its smaller child while that child is smaller. The smaller one, so the new parent is no bigger than the other child. 8 swaps with 2, then with 4. Index 3 has no children left, so it stops.
Why it is fast
Each swap moves one level. A complete tree of n items has ⌊log₂ n⌋ + 1 levels, so a sift makes at most ⌊log₂ n⌋ swaps: 3 for 8 items, 19 for a million. Push and pop are O(log n); reading h[0] is O(1).
Python's heapq module does exactly this to a plain list. heappush(h, 1) then heappop(h) returns 1 and leaves h = [2, 4, 3, 8, 5, 7, 6] again. It is a min-heap; Python 3.14 adds heappush_max and heappop_max for a max-heap.
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.