Lesson · Useful Standard Library Collections
heapq
55 min readheapq
`heapq` implements a binary min-heap on a list. It is the standard tool for priority queues, top-k selection, and algorithms that repeatedly need the smallest item.
Learning goals
- Use
heapifyto turn a list into a valid min-heap and point to the one position whose value is guaranteed. - Push and pop with
heappushandheappop, and describe the invariant each call restores. - Explain why heap order is weaker than sorted order and what that means for iterating the list.
- Choose
nlargestornsmallestfor top-k selection and say when they beat a full sort. - Build a tuple-based priority queue and add a tie-breaker so equal priorities cannot raise
TypeError.
Mental model
The invariant is local: every parent is no larger than its children, which is enough to keep the smallest item findable at index 0 without sorting the whole list. Push and pop each spend about log n comparisons restoring that invariant, so the structure stays cheap for repeated smallest-first work.
Mental model
read it top to bottom
plain list ↓ heapify: arrange into heap order min-heap index 0 holds the smallest item ↓ heappush: sift up ↓ heappop: sift down min-heap still valid items leave in ascending order
Core idea
A heap is a list wearing an ordering guarantee: heapify arranges it, heappush and heappop maintain it, and the only promise is that the smallest item sits at index 0. Because the rest of the list is deliberately unsorted, heaps win at repeated smallest-first access and lose at full ordering, so reach for sorted when everything must be in order and nlargest or nsmallest when only one end of it matters.
Min-heaps
A min-heap is a complete binary tree stored in a list where every parent is no larger than its children. The only positional guarantee is that the smallest item sits at index 0; the rest of the list is in heap order, not sorted order.
Push/pop
heapq.heappush inserts an item and sifts it up until the invariant holds, while heapq.heappop removes and returns the smallest item and then sifts the last entry down from the root. Both mutate the list in place and cost time proportional to the logarithm of the heap size; heappush returns None.
heapify
heapq.heapify rearranges an existing list into heap order in linear time. Heap order guarantees only that the smallest item is at index zero, not that the list is globally sorted.
nlargest
nlargest returns the largest few items efficiently for small n relative to the input. It scans the iterable once while holding at most n candidates in a min-heap, accepts a key function, and returns the items in descending order.
nsmallest
nsmallest returns the smallest few items efficiently for small n relative to the input. It keeps at most n candidates in a max-heap while scanning, accepts the same key argument as sorted, and returns the items in ascending order.
Priority queues
A priority queue removes work according to priority rather than insertion order. heapq supplies the heap primitive, while your data model must define how equal priorities are ordered.
Walkthrough
heapq.heapify([7, 2, 9, 1])rearranges the list in place into[1, 2, 9, 7]: index 0 holds the smallest item, but nothing else is sorted, and no new list is allocated.heapq.heappush(heap, 3)appends3and sifts it up past larger parents; the call mutatesheapand returnsNone, so never rebind the name to its result.- The
while heap:loop pops five times and prints1, 2, 3, 7, 9:heappopremoves the smallest item, moves the last entry to the root, and sifts it down until the heap is valid again. - Predict before running: the order of the five printed numbers, whether the list is fully sorted before the first pop, and what
heappushhands back.
Experiments to try
- Rebuild
[7, 2, 9, 1], callheapifyonly, and print the result next tosorted(...); note which single position the heap guarantees. - Rebind
heap = heapq.heappush(heap, 5)and then callheapq.heappop(heap); read the resultingTypeErrorand explain which contract was ignored. - Push
(2, "write")and(2, "review")tuples and pop them; then push a tuple whose second element is a dict and read the comparison error when priorities tie. - Call
heapq.nlargest(3, numbers)andheapq.nsmallest(3, numbers)on the same 20-item list and check each result against the matchingsorted(numbers)slice.
Common mistakes
- Iterating a heap to read it in sorted order: heap order only pins the smallest item to index 0, so a
forloop over the list prints an arrangement, not a sequence; drain the heap withheappopfor ascending output. - Rebinding the result of
heappush: the call mutates the list in place and returnsNone, soheap = heapq.heappush(heap, x)replaces the heap withNoneand the next operation fails. - Using plain tuples for a priority queue without a tie-breaker: when two entries share a priority, Python compares the next tuple element, and non-comparable payloads raise
TypeError; add an increasing counter as the second element. - Expecting an update or delete operation other than pop:
heapqoffers no decrease-key or arbitrary removal, so the standard technique is lazy deletion, pushing the new entry and discarding stale ones when they surface.
Practice: Easy
- Run the worked example, then rebuild the list and call
heapifyagain; print the heap and mark which single position is guaranteed to hold the smallest value. - Rebind
heap = heapq.heappush(heap, 5), callheapq.heappop(heap), and explain the resultingTypeErrorusing the in-place contract. - Call
heapq.nlargest(2, [4, 1, 7, 3])andheapq.nsmallest(2, [4, 1, 7, 3])and check each result against the matchingsortedslice.
Practice: Medium
- Build a priority queue of
(priority, task)pairs with three equal priorities and pop everything; then replace the payload with a dictionary and report where the comparison breaks. - Write two versions of a function that returns the three highest scores, one with
nlargest(3, scores)and one withsorted(scores)[-3:]; compare the results on 10,000 generated numbers and time both withtime.perf_counter(). - Convert a loop that repeatedly scans a list for the smallest remaining item into
heapifyplusheappop; state what each extraction costs in both versions.
Practice: Hard
- Design a small task scheduler on a heap: entries as
(priority, sequence, name)with an increasing counter as the tie-breaker, and functionsadd(task, priority)andrun_next()that define what happens when the heap is empty. - Failure lab: trigger the three classic traps, a
Nonerebound fromheappush, a sorted-order expectation from iterating the raw list, and aTypeErrorfrom comparing tied tuples with non-comparable payloads; explain the mechanism behind each. - Connect this lesson to the performance module: explain when
nlargestcan beat sorting an entire stream and design a timing comparison that shows the crossover point asngrows.
Lesson checklist
- I can heapify a list and point to the only position whose value is guaranteed.
- I can trace a push and a pop and describe the sift that restores the invariant.
- I can build a tuple-based priority queue that survives equal priorities.
- I can pick
nlargestornsmallestover a full sort when only one end of the ordering matters.
Remember
`heapq` keeps a plain list in heap order: index 0 holds the smallest item, and `heappush` and `heappop` restore that invariant in logarithmic time, which keeps repeated smallest-first work cheap. The list is deliberately not sorted, so drain a heap with pops when you need full order and use `nlargest` or `nsmallest` when only a few extremes matter.
Interview angles
What is the main purpose of **Min-heaps**?+
A min-heap is a list arranged so every parent is no larger than its children, which pins the smallest item to index 0. The heapq functions maintain that arrangement and only that arrangement: the rest of the list is in heap order, not sorted order.
What should you pay attention to when using **Push/pop**?+
Both work on the list in place: heappush inserts a value and returns None, while heappop removes and returns the smallest item. Either call restores the heap invariant with about log n comparisons.
How does **heapify** fit into this lesson?+
heapq.heapify rearranges an existing list into heap order in linear time. Heap order guarantees only that the smallest item is at index zero, not that the list is globally sorted.
Why does a `for` loop over a heap not print a sorted sequence?+
Heap order only guarantees that each parent is no larger than its children, which pins the smallest item to index 0 and nothing else; draining the heap with heappop is what produces ascending order.