Code Snippets
/

heapq Min-Heap Recipes

heapq Min-Heap Recipes

Python's `heapq` module turns any list into a binary min-heap in place, supporting O(log n) push and pop. It is the priority-queue primitive that powers Dijkstra, Top-K, and merging sorted streams. This snippet covers the basic push and pop, the Top-K largest pattern using `nsmallest` and `nlargest`, and the merge of multiple sorted iterables in O(N log K).

Python
Medium
3 snippets
py-standard-library
heap
code-template
algorithms

587 views

17

import heapq

heap = []
for x in [5, 3, 7, 1, 9, 2]:
    heapq.heappush(heap, x)

print(heap)             # [1, 3, 2, 5, 9, 7] (heap-ordered, not sorted)
print(heap[0])          # 1 (smallest)

out = []
while heap:
    out.append(heapq.heappop(heap))
print(out)              # [1, 2, 3, 5, 7, 9]

heapq operates directly on a Python list, treating it as a binary heap with heap[0] as the smallest element. heappush and heappop are both O(log n). Note that the heap is NOT sorted: it satisfies the heap invariant (parent <= children), but the in-memory order can look scrambled. Reading heap[0] gives an O(1) min query, which is the headline operation. To sort, repeatedly pop until empty (heap sort), which is O(n log n) total.