Sub topic 11
Sorting with Python's heapq Module
The earlier chapters built heap sort by hand: sift_down, build_max_heap, and an in-place loop that swaps the root to the end of the array. Python's standard library ships a heap in the heapq module, written in C. This chapter shows how to sort with it, where it differs from the hand-built version, and when a heap is the wrong tool for sorting in Python.
This chapter assumes you can read Python functions and list comprehensions, know Big-O notation, and have followed the earlier chapters on sift-down, bottom-up heap construction, and in-place heap sort.
What heapq Gives You
heapq does not define a heap class. It provides functions that treat an ordinary Python list as a binary heap, using the same index arithmetic as before: the children of index i are at 2*i + 1 and 2*i + 2.
The main difference is the direction of the order. heapq keeps a min-heap, meaning every parent is less than or equal to its children. The smallest element is always at h[0].
| Function | What it does | Time |
|---|---|---|
| `heapify(h)` | Rearranges list `h` into a min-heap in place | O(n) |
| `heappush(h, x)` | Adds `x` and sifts it up | O(log n) |
| `heappop(h)` | Removes and returns the smallest element | O(log n) |
| `heappushpop(h, x)` | Pushes `x`, then pops the smallest; faster than doing both separately | O(log n) |
| `heapreplace(h, x)` | Pops the smallest, then pushes `x`; the heap size stays the same | O(log n) |
| `nsmallest(k, it, key=None)` | Returns the `k` smallest items, sorted | O(n log k) |
| `nlargest(k, it, key=None)` | Returns the `k` largest items, sorted | O(n log k) |
| `merge(*its, key=None, reverse=False)` | Lazily merges already-sorted iterables | O(n log m) for m inputs |
heapify uses the same bottom-up construction you proved linear in the previous chapter. Its sift step works a little differently from our sift_down. It moves the smaller child up at every level until it reaches a leaf, then sifts the saved item back up a short way. This saves comparisons on average, and a later chapter covers it as "bottom-up heap sort". The arrays it produces can therefore differ from the ones our hand-written code produces, but both are valid heaps.
The Basic heapq Sort
With a min-heap, sorting means popping until the heap is empty. Each pop returns the smallest remaining element, so the output comes out in ascending order.
import heapq
def heapq_sort(items):
h = list(items) # copy, so the caller's data is untouched
heapq.heapify(h) # O(n)
return [heapq.heappop(h) for _ in range(len(h))] # n pops, O(log n) each
print(heapq_sort([5, 2, 9, 1, 7, 3])) # [1, 2, 3, 5, 7, 9]The range(len(h)) is evaluated once, before any pops, so the loop runs exactly n times even though h shrinks.
The total cost is O(n) for heapify plus n pops at O(log n) each. That is O(n log n) in every case, the same bound as the hand-written version.
Why This Version Is Not In Place
The in-place algorithm depended on a heap that shrinks from the right. After each swap, the sorted tail sat beyond an end index that sift_down ignored. The heapq functions take no end parameter. They treat the entire list as the heap, rooted at index 0. heappop removes the last element of the list, puts it at the root, and sifts it down. The list really shrinks, so there is no unused tail where results could be stored.
You therefore need a second list for the output, which costs O(n) extra space. You give up the O(1) space advantage that makes heap sort interesting in the first place.
Descending Order and Max-Heaps
To sort in descending order with a min-heap, a common trick for numbers is to negate them:
import heapq
def heapq_sort_desc(nums):
h = [-x for x in nums]
heapq.heapify(h)
return [-heapq.heappop(h) for _ in range(len(h))]
print(heapq_sort_desc([5, 2, 9, 1, 7, 3])) # [9, 7, 5, 3, 2, 1]Negation works only for numeric keys. It fails on strings and on any type without unary minus.
Python 3.14 added public max-heap functions: heapify_max, heappush_max, heappop_max, heapreplace_max, and heappushpop_max. On 3.14 or later you can write the descending sort directly:
import heapq
def heapq_sort_desc_314(items):
h = list(items)
heapq.heapify_max(h)
return [heapq.heappop_max(h) for _ in range(len(h))]
print(heapq_sort_desc_314(["pear", "apple", "fig"])) # ['pear', 'fig', 'apple']Sorting Records by a Key
heappush and heappop take no key argument. To sort records by a field, you decorate each item: you wrap it in a tuple whose first element is the sort key. Tuples compare element by element, so the heap orders entries by the key first.
The decoration also fixes a problem covered in the chapter on stability. Plain heap sort is not stable, because equal keys can be reordered during sifting. If you add each item's original position as a second tuple element, no two entries are ever equal, and ties are broken by original order:
import heapq
def stable_heapq_sort(records, key):
h = [(key(r), i, r) for i, r in enumerate(records)]
heapq.heapify(h)
return [heapq.heappop(h)[2] for _ in range(len(h))]
scores = [("bob", 3), ("amy", 1), ("cat", 3), ("dan", 1)]
print(stable_heapq_sort(scores, key=lambda r: r[1]))
# [('amy', 1), ('dan', 1), ('bob', 3), ('cat', 3)]Bob comes before Cat and Amy comes before Dan, which matches the input order. The algorithm underneath is still unstable. The output is stable only because the index makes every key unique. The cost is an extra tuple per element and slower tuple comparisons.
The Tie-Breaker Also Prevents Crashes
The index has a second job. If two keys are equal and the tuple has no index, Python goes on to compare the records themselves. Many types do not support <:
import heapq
tasks = [(2, {"name": "write"}), (2, {"name": "test"})]
try:
heapq.heapify(tasks)
heapq.heappop(tasks)
heapq.heappop(tasks)
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'dict' and 'dict'With (priority, i, task) entries, the comparison stops at the unique i and never reaches the dicts. The heapq documentation recommends the same pattern for priority queues.
Partial Sorting: Where heapq Pays Off
heapq rarely wins for a full sort. It is useful when you need only part of the sorted order.
nsmallest(k, data) keeps a heap of size k while it scans the data, so it runs in O(n log k) time and O(k) memory. When k is much smaller than n, that costs much less than sorting everything.
import heapq
data = [42, 7, 19, 88, 3, 56, 21, 64, 11]
print(heapq.nsmallest(3, data)) # [3, 7, 11]
print(heapq.nlargest(3, data)) # [88, 64, 56]
people = [("ana", 31), ("ben", 25), ("cy", 40), ("di", 25)]
print(heapq.nsmallest(2, people, key=lambda p: p[1]))
# [('ben', 25), ('di', 25)]Unlike heappush and heappop, nsmallest and nlargest accept a key. Their results are equivalent to sorted(data, key=key)[:k], and that equivalence includes stable ordering of ties.
merge covers a different case. It takes inputs that are already sorted and produces one sorted stream without loading everything into memory. It keeps one heap entry per input:
import heapq
a = [1, 4, 7]
b = [2, 5, 8]
c = [3, 6, 9]
print(list(heapq.merge(a, b, c))) # [1, 2, 3, 4, 5, 6, 7, 8, 9]This is the final step of an external sort: you sort chunks that fit in memory, write them to disk, and then merge the chunk files.
Choosing the Right Tool
For a full sort in Python, use sorted() or list.sort(). Both use Timsort, which is stable, implemented in C, and runs in O(n) time on input that is already sorted or nearly sorted. A heapq_sort pays for n separate heappop calls and their sift operations, so it is usually several times slower. You can check this on your own machine:
import heapq
import random
import timeit
def heapq_sort(items):
h = list(items)
heapq.heapify(h)
return [heapq.heappop(h) for _ in range(len(h))]
data = [random.random() for _ in range(100_000)]
assert heapq_sort(data) == sorted(data)
print("sorted(): ", timeit.timeit(lambda: sorted(data), number=10))
print("heapq_sort: ", timeit.timeit(lambda: heapq_sort(data), number=10))The heapq documentation gives the same advice for k. When k is 1, min() and max() are faster. When k approaches n, sorting and slicing is faster.
| Approach | Time | Extra space | Stable |
|---|---|---|---|
| Hand-written in-place heap sort | O(n log n) | O(1) | No |
| `heapq_sort` (plain values) | O(n log n) | O(n) | Not meaningful for plain values; equal ones are indistinguishable |
| `heapq_sort` with `(key, i, item)` | O(n log n) | O(n) | Yes |
| `sorted()` (Timsort) | O(n log n), O(n) on sorted runs | O(n) | Yes |
| `nsmallest(k, ...)` | O(n log k) | O(k) | Yes |
Exercise
A colleague writes h = data; heapq.heapify(h); out = [heapq.heappop(h) for _ in range(len(h))] and is surprised that data is empty afterward. Explain why and fix it.
Show answer
h = data copies only the reference, so h and data are the same list object. heapify rearranges that list in place, and each heappop removes an element from it, so data ends up empty. Make a copy first with h = list(data) (or data.copy()). The rest of the code can stay the same.
Exercise
Write a function top_k_stable(records, k, key) that returns the k records with the largest keys, largest first, and breaks ties by original position without calling nlargest. Your function must work when the records are dicts. What is its time complexity?
Show answer
Keep a min-heap of size k holding (key, -i, i) entries. The root is then the weakest entry, meaning the smallest key with the latest position among equal keys. For each record i: if the heap has fewer than k entries, push (key(r), -i, i). Otherwise, if (key(r), -i) is greater than the root's first two fields, call heapreplace with the new entry. At the end, sort the heap entries in descending order and map each one back to records[i]. Example: def top_k_stable(records, k, key): h = []; for i, r in enumerate(records): e = (key(r), -i, i); if len(h) < k: heapq.heappush(h, e); elif e > h[0]: heapq.heapreplace(h, e); then return [records[i] for _, _, i in sorted(h, reverse=True)]. The tuples never reach the dicts because -i is unique. Each of the n records costs at most O(log k), and the final sort costs O(k log k), so the total is O(n log k) time with O(k) extra space.
Exercise
Why can't you implement the O(1)-extra-space heap sort using only heapq.heapify, heappop, and heappush on a single list?
Show answer
The heapq functions always treat the whole list as the heap, with the root at index 0, and they take no end boundary. In-place heap sort needs to swap the root into a tail region and then sift down while ignoring that tail. heappop removes the last element, so the list shrinks and the popped values have to be stored somewhere else, which costs O(n) extra space. Doing it in place requires your own sift-down that accepts an end index, like the one from earlier chapters.