On this page
heapq
Prev: hashlib | Up: stdlib_module | Next: hmac
Rel: datetime, zoneinfo, calendar, collections, bisect
Ref: docs.python.org — heapq
Tags: #public #python3 #stdlib
Import
import heapq
Overview
In-place binary min-heap operations on ordinary Python lists (heappush, heappop, heapify, nlargest, nsmallest, merge). Reach for heapq for priority queues, Dijkstra/A* search, top-K streaming selection, and merging multiple sorted iterables in O(log n) per step.
Quick Start
import heapq
nums = [9, 2, 7, 1, 5]
heapq.heapify(nums) # O(n) in-place min-heap
assert heapq.heappop(nums) == 1
heapq.heappush(nums, 0)
assert heapq.heappop(nums) == 0
Implementation Walkthrough
1. Priority Queue with Tie-Breaker Counter
When items have equal priority, Python compares the next tuple element—include a monotonic counter so unorderable payloads (like dicts or objects) never trigger TypeError:
import heapq
import itertools
counter = itertools.count()
pq: list[tuple[int, int, dict[str, str]]] = []
def push(priority: int, task: dict[str, str]) -> None:
heapq.heappush(pq, (priority, next(counter), task))
push(2, {"name": "low"})
push(1, {"name": "urgent-a"})
push(1, {"name": "urgent-b"})
order = [heapq.heappop(pq)[2]["name"] for _ in range(3)]
assert order == ["urgent-a", "urgent-b", "low"]
2. Streaming Top-K & Merging Sorted Iterables
import heapq
top3 = heapq.nlargest(3, [4, 1, 9, 7, 2, 8])
assert top3 == [9, 8, 7]
merged = list(heapq.merge([1, 4, 7], [2, 3, 8], [0, 9]))
assert merged == [0, 1, 2, 3, 4, 7, 8, 9]
Gotchas & Boundaries
- Min-heap only (smallest item pops first): For a max-heap on numbers, negate the priority (
-score)—or useheapq.heappush_max/heapq.heappop_maxif available in your Python version. - Do not mutate a heap list directly (
list.append()or slicing breaks the heap invariant); always useheappush/heappop/heapreplace. - For
kclose tolen(data),sorted(data)[:k]is faster thannsmallest(k, data);nlargest/nsmallestshine whenk << n.
Common Functions
- heapq.heapify() —
heapify(heap, /)— Transform list into a heap, in-place, in O(len(heap)) time. - heapq.heapify_max() —
heapify_max(heap, /)— Maxheap variant of heapify. - heapq.heappop() —
heappop(heap, /)— Pop the smallest item off the heap, maintaining the heap invariant. - heapq.heappop_max() —
heappop_max(heap, /)— Maxheap variant of heappop. - heapq.heappush() —
heappush(heap, item, /)— Push item onto heap, maintaining the heap invariant. - heapq.heappush_max() —
heappush_max(heap, item, /)— Push item onto max heap, maintaining the heap invariant. - heapq.heappushpop() —
heappushpop(heap, item, /)— Push item on the heap, then pop and return the smallest item from the heap. - heapq.heappushpop_max() —
heappushpop_max(heap, item, /)— Maxheap variant of heappushpop. - heapq.heapreplace() —
heapreplace(heap, item, /)— Pop and return the current smallest value, and add the new item. - heapq.heapreplace_max() —
heapreplace_max(heap, item, /)— Maxheap variant of heapreplace. - heapq.merge() —
merge(*iterables, key=None, reverse=False)— Merge multiple sorted inputs into a single sorted output. - heapq.nlargest() —
nlargest(n, iterable, key=None)— Find the n largest elements in a dataset. - heapq.nsmallest() —
nsmallest(n, iterable, key=None)— Find the n smallest elements in a dataset.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/bisect
- tuts/python3/stdlib_module/calendar
- tuts/python3/stdlib_module/collections
- tuts/python3/stdlib_module/copy
- tuts/python3/stdlib_module/datetime
- tuts/python3/stdlib_module/enum
- tuts/python3/stdlib_module/graphlib
- tuts/python3/stdlib_module/hashlib
- tuts/python3/stdlib_module/heapq/heapify
- tuts/python3/stdlib_module/heapq/heapify_max
- tuts/python3/stdlib_module/heapq/heappop
- tuts/python3/stdlib_module/heapq/heappop_max
- tuts/python3/stdlib_module/heapq/heappush
- tuts/python3/stdlib_module/heapq/heappush_max
- tuts/python3/stdlib_module/heapq/heappushpop
- tuts/python3/stdlib_module/heapq/heappushpop_max
- tuts/python3/stdlib_module/heapq/heapreplace
- tuts/python3/stdlib_module/heapq/heapreplace_max
- tuts/python3/stdlib_module/heapq/merge
- tuts/python3/stdlib_module/heapq/nlargest
- tuts/python3/stdlib_module/heapq/nsmallest
- tuts/python3/stdlib_module/hmac
- tuts/python3/stdlib_module/pprint
- tuts/python3/stdlib_module/reprlib
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/types
- tuts/python3/stdlib_module/weakref
- tuts/python3/stdlib_module/zoneinfo
Related notes
- tuts/python3/stdlib_module/bisect Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/datetime Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/hashlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heapify Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heapify_max Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heappop Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heappop_max Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heappush Linked here; links to this page; shared tags: #stdlib