`heapq`
heapq is the standard-library heap: a min-heap stored in a list. heappush and heappop keep the smallest item at index 0 in O(log n) time.
Detailed Explanation
A heap is a binary tree where each parent is smaller than its children (a min-heap). heapq stores that tree in a list using the usual index rule: children of i are 2*i+1 and 2*i+2. You do not build the tree yourself. You keep a list and only touch it through heapq functions.
heappush(heap, item) adds an item. heappop(heap) removes and returns the smallest. heap[0] peeks. heapify(list) rearranges an existing list into a heap in O(n). heappushpop and heapreplace combine a push and a pop more efficiently than the two calls.
The heap is a min-heap of whatever Python compares. For a max-heap, push negated numbers, or push tuples with a leading minus. For items that are not comparable, push (priority, tie_breaker, payload) so the heap never needs to compare the payloads. A running counter as tie_breaker also stops TypeError when two priorities are equal and the objects have no <.
There is no decrease-key. The usual workaround is to push a new entry and mark the old one as stale, then skip stale entries on pop. That is how Dijkstra is often written in Python.
nlargest(n, iterable) and nsmallest use a heap internally. They are the right tool for "top ten" on a large stream. Sorting the whole list is simpler when n is close to the length.
heapq is not thread-safe. It is not a blocking queue. For producers and consumers, use queue.PriorityQueue (which wraps heapq with a lock) or an asyncio priority structure you control.
Code Examples
import heapq
due = []
heapq.heappush(due, (2, "ship"))
heapq.heappush(due, (1, "pay"))
heapq.heappush(due, (3, "email"))
print(heapq.heappop(due)) # (1, 'pay')
print(due[0]) # (2, 'ship') peek# Stable priorities: a counter avoids comparing payloads.
import itertools
seq = itertools.count()
heap: list = []
heapq.heappush(heap, (5, next(seq), {"sku": "A-1"}))
heapq.heappush(heap, (5, next(seq), {"sku": "B-2"}))
print(heapq.heappop(heap)[2]["sku"]) # A-1print(heapq.nsmallest(3, [9, 1, 4, 7, 2])) # [1, 2, 4]Common Gotchas
Mutating the list with `sort` or `append` breaks the heap
only `heapq` operations (and `heap[0]` reads) are legal.
Equal priorities compare the rest of the tuple
incomparable payloads raise `TypeError`. Add a unique tie-breaker.
No max-heap builtin
negate the priority, or you will pop the wrong end.
`heap[0]` is a peek, not a pop
it leaves the heap unchanged. `heappop` is the removal.