Sub topic 11
Sorting with Python's heapq Module
This chapter assumes you know the max-heap property, sift-down, and bottom-up heap construction from earlier chapters. You should also be comfortable with Python lists and tuples. Here you'll use the standard library's heapq module to sort, and see how that differs from the in-place heap sort you wrote by hand.
What heapq Gives You
The heapq module works on an ordinary Python list and treats it as a binary heap. It uses the same index arithmetic as before: the children of index i are at 2*i + 1 and 2*i + 2. There is one major difference. heapq maintains a min-heap, so the smallest element sits at index 0.
The core functions are:
| Function | What it does | Cost |
|---|---|---|
| `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 item, then sifts down | O(log n) |
| `nsmallest(k, it)` | Returns the k smallest items | about O(n log k) |
| `nlargest(k, it)` | Returns the k largest items | about O(n log k) |
A Heap Sort in Three Lines
Because the root is always the minimum, popping repeatedly returns the elements in ascending order.
import heapq
def heapq_sort(items):
h = list(items)
heapq.heapify(h)
return [heapq.heappop(h) for _ in range(len(h))]
print(heapq_sort([5, 2, 9, 1, 7, 3])) # [1, 2, 3, 5, 7, 9]The total time is still O(n log n): one linear heapify, then n pops at O(log n) each. The space cost is different, though. The function copies the input and builds a second list for the output, so it uses O(n) extra memory. Your hand-written version avoided that extra memory by swapping the root into the shrinking tail of the same array.
Descending Order and Max-Heaps
To sort numbers from largest to smallest, a common trick is to negate the values on the way in and again on the way out:
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 numbers. Python 3.14 added public max-heap functions such as heapify_max and heappop_max, which work for any comparable values.
Sorting by a Key, Stably
heapq functions take no key argument. To sort by a key, wrap each item in a tuple. If you include the original position as a tiebreaker, you get two benefits. Equal keys come out in their input order, which makes the sort stable. Python also never has to compare the items themselves, which matters when the items can't be compared.
import heapq
def heapq_sort_by(items, key):
h = [(key(x), i, x) for i, x in enumerate(items)]
heapq.heapify(h)
return [heapq.heappop(h)[2] for _ in range(len(h))]
records = [("bob", 3), ("amy", 1), ("cat", 3), ("dan", 2)]
print(heapq_sort_by(records, key=lambda r: r[1]))
# [('amy', 1), ('dan', 2), ('bob', 3), ('cat', 3)]The index makes every tuple unique. Heap sort on its own is unstable, as the previous chapter showed. Here the stability comes from the tiebreaker, not from the heap.
When to Use heapq
To fully sort a list in Python, call sorted() or list.sort(). They use Timsort, which is stable, implemented in C, and fast on partially ordered data. heapq is the better choice in these cases:
- You need only the top k items.
heapq.nsmallest(3, data)avoids sorting everything. - Items arrive over time and you always need the current minimum, as in a priority queue or a scheduler.
- You are merging already-sorted streams.
heapq.mergedoes this lazily.
import heapq
data = [5, 2, 9, 1, 7, 3]
print(heapq.nsmallest(3, data)) # [1, 2, 3]
print(heapq.nlargest(2, data)) # [9, 7]Exercise
The heapqsort function above runs in O(n log n) time, the same as the in-place heap sort from the earlier chapter. Name one way the two differ in resource use, and explain why heapqsort pays that cost.
Show answer
heapqsort uses O(n) extra memory, while the in-place version uses O(1). heapqsort copies the input into a new list and collects the popped elements into a separate output list. The in-place version swaps each maximum into the end of the same array, where the heap has just shrunk.
Exercise
Why does heapqsortby put the index i between the key and the item in each tuple, instead of storing just (key, item)?
Show answer
When two keys are equal, Python compares the next tuple element. With (key, item), it would compare the items, which can fail or reorder ties. With a unique index, ties are broken by input position, so the sort is stable and the items themselves are never compared.