Section 15.27

heapq module

Full name: heapq: a name formed from heap and q, for queue; the Python documentation calls the module’s algorithm the heap queue algorithm.

Definition

The heapq module is the module of the Python §12.23 standard library that keeps an ordinary Python list arranged as a binary min-heap. In that arrangement the item at each position kk is less than or equal to the items at positions 2k+12k+1 and 2k+22k+2, called its children, so the smallest item is always at position 0. Adding an item and removing the smallest each take time at most proportional to the logarithm of the number of items. The module is the usual way to build a priority queue §14.16 in Python.

The idea

A program that runs timed tasks must repeatedly find the task with the earliest deadline while new tasks keep arriving. A fully sorted list makes the earliest task easy to find, but each insertion must shift later items to make room, which takes time proportional to the number of items. An unsorted list makes insertion cheap, but each removal must search every item.

A heap does the ordering work that finding the minimum needs, and no more. Picture the list as a family tree: position 0 is the root, and positions 2k+12k+1 and 2k+22k+2 are the two children of position kk. The heap rule says only that a parent is never larger than its children. Along any line of descent, values therefore never decrease, so the root holds the smallest item. Two items on different branches, such as two siblings, may stand in either order. That freedom is why the list is not sorted, and it is also what makes changes cheap: an insertion or a removal repairs a single line of descent, which for nn items is only about log2n\log_2 n positions long.

How it works

Positions. In a list h of length nn, the item at index kk has its children at indices 2k+12k+1 and 2k+22k+2, where those are less than nn. Every index i>0i > 0 has its parent at index ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor, where ⌊y⌋\lfloor y \rfloor means yy rounded down to a whole number. The tree is stored level by level without gaps, so the list needs no pointers between items.

Operations.

  1. heappush(h, x) appends xx at the end of the list. Then, while xx is smaller than its parent, it swaps xx with the parent. This is called sifting up.

  2. heappop(h) removes and returns the smallest item, h[0]. It moves the last item of the list to index 0. Then, while one of that item’s children is smaller than it, it swaps the item with its smaller child. This is called sifting down. The module’s own code uses a variant that makes fewer comparisons and restores the same rule.

  3. h[0] reads the smallest item without removing it.

  4. heapify(h) rearranges any list into a heap, in place.

Further functions build on these: heappushpop and heapreplace push and pop in one call, nsmallest and nlargest return a given number of the smallest or largest items of any collection, and merge combines sorted inputs into one sorted output.

Comparisons. The module compares items only with the less-than operator <. To attach a task to a priority, push tuples (priority, count, task), where count increases by one with every push. Tuples compare element by element, so a tie in priority is decided by count. Tasks of equal priority then come out first in, first out §14.14 (FIFO), and two tasks are never compared with each other, which matters when tasks do not support <. For largest-first order, push the negated priority.

Costs. For nn items, a push or a pop makes a number of comparisons at most proportional to log2n\log_2 n, written O(logn)O(\log n) in Big-O notation §14.2, the usual notation for how a cost grows with the size of the input. Reading h[0] takes constant time, and heapify takes time proportional to nn. For a million items, log21,000,000≈19.9\log_2 1{,}000{,}000 \approx 19.9, so a path from the root to the bottom has at most 20 positions.

Worked example

Push 5, 3, 8, 1, 4 and 2, in that order, onto an empty list h. Each new item starts at the end, at some index ii, and is compared with its parent at index ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor.

  1. Push 5: h is [5].

  2. Push 3 at index 1. Its parent, index 0, holds 5, and 3<53 < 5, so swap: [3, 5].

  3. Push 8 at index 2. Its parent, index ⌊1/2⌋=0\lfloor 1/2 \rfloor = 0, holds 3, and 8≥38 \ge 3, so stop: [3, 5, 8].

  4. Push 1 at index 3. Its parent, index ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1, holds 5, and 1<51 < 5, so swap: [3, 1, 8, 5]. Index 1’s parent, index 0, holds 3, and 1<31 < 3, so swap again: [1, 3, 8, 5].

  5. Push 4 at index 4. Its parent, index ⌊3/2⌋=1\lfloor 3/2 \rfloor = 1, holds 3, and 4≥34 \ge 3, so stop: [1, 3, 8, 5, 4].

  6. Push 2 at index 5. Its parent, index ⌊4/2⌋=2\lfloor 4/2 \rfloor = 2, holds 8, and 2<82 < 8, so swap: [1, 3, 2, 5, 4, 8]. Index 2’s parent, index 0, holds 1, and 2≥12 \ge 1, so stop.

Check the rule at every parent of [1, 3, 2, 5, 4, 8]. Index 0 holds 1, and its children at indices 1 and 2 hold 3 and 2. Index 1 holds 3, and its children at 2×1+1=32 \times 1 + 1 = 3 and 2×1+2=42 \times 1 + 2 = 4 hold 5 and 4. Index 2 holds 2, and its only child, at 2×2+1=52 \times 2 + 1 = 5, holds 8. Every parent is at most its children, so the list is a valid heap, yet it is not sorted: 3 stands before 2, and 5 before 4. Both pairs are siblings, not parent and child, so the rule says nothing about their order.

Now pop. heappop returns h[0], which is 1, and moves the last item, 8, to index 0: [8, 3, 2, 5, 4]. The children of index 0 hold 3 and 2; the smaller is 2, and 2<82 < 8, so swap: [2, 3, 8, 5, 4]. Index 2 would have children at indices 5 and 6, but the list now ends at index 4, so 8 stays. Popping the remaining items returns 2, 3, 4, 5 and 8: repeated pops give sorted order, although the list itself was never sorted.

Stated precisely

A list hh of length nn is a heap when h[k]≤h[2k+1] for every k with 2k+1<n,h[k]≤h[2k+2] for every k with 2k+2<n.h[k] \le h[2k+1] \ \text{ for every } k \text{ with } 2k+1 < n, \qquad h[k] \le h[2k+2] \ \text{ for every } k \text{ with } 2k+2 < n. Because the module evaluates only <, a≤ba \le b here means that b<ab < a is false. Call index jj an ancestor of index ii if moving from ii to its parent one or more times reaches jj. The rule orders exactly the pairs in which one index is an ancestor of the other. Since 0 is an ancestor of every other index, h[0]h[0] is a smallest item. Every sorted list satisfies the rule, but a heap of three or more distinct items need not be sorted.

The module’s guarantees rest on three assumptions.

  1. The items’ < is a strict weak ordering: no item is less than itself; if a<ba < b and b<cb < c, then a<ca < c; and being tied, meaning that neither item is less than the other, is transitive too. Integers, strings, floating-point numbers §4.49 other than NaN (not a number), and tuples whose corresponding elements are such values satisfy this.

  2. The list is changed only through the module’s functions, or is passed to heapify again after any other change.

  3. No item’s priority changes while the item is in the heap.

Under these assumptions, every heappush and heappop leaves a heap, heappop returns a smallest item, and nn successive pops return the items in non-decreasing order. Items with equal priority come out in no guaranteed order unless a counter is added.

Limits and common mistakes

The list is not a sorted list. Iterating over it or printing it does not give priority order; pop the items one at a time, or call sorted(h) for a sorted copy.

Changing a priority in place breaks the rule without any error. Either call heapify again, at a cost proportional to nn, or, as the module’s documentation suggests, mark the old entry as removed, push a new entry, and skip removed entries when they are popped.

A comparison that is not a strict weak ordering corrupts the order without any error. Every < comparison involving NaN is false, so pushing 1, NaN, 3, 2 and 4 and then popping five times returns 1, 3, 2, NaN, 4: the 3 comes out before the 2.

Equal priorities with payloads that cannot be compared raise an exception. Pushing (1, {'a': 1}) and then (1, {'b': 2}) raises TypeError, because the tie forces a comparison of two dictionaries. The counter described above prevents this.

The module makes no promise about concurrent use. When several threads share one heap, protect it with a lock, or use queue.PriorityQueue from the standard library, which wraps the same algorithm §14.1 with a lock.

The name has nothing to do with heap storage §4.11, the region of memory from which a program allocates objects while it runs; the two uses share only the word.

Questions answered

Why is the whole heap array §14.5 not globally sorted?

A heap array is not globally sorted because the heap rule orders only each parent against its own children, and that partial order §19.2.6 is all a priority queue needs. In Python’s heapq module the rule is that the item at index kk is less than or equal to the items at indices 2k+12k+1 and 2k+22k+2. Following parents upwards, values never increase, so index 0 always holds the smallest item. Two items of which neither is the other’s ancestor, such as two siblings, may stand in either order: the list [1, 3, 2, 5, 4, 8] satisfies the rule, yet 3 stands before 2.

Keeping only this partial order is deliberate. An insertion or a removal then repairs one path of about log2n\log_2 n positions for nn items, whereas keeping the whole array sorted would require shifting up to nn items on each insertion. To obtain all items in order, pop them one at a time, or sort a copy of the list.

Related entries: Priority queue (§14.16), Asymptotic complexity (§14.2), Python (§12.23), Static, stack, and heap storage (§4.11). Further reading: [144].