On this page
  1. heapq
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Priority Queue with Tie-Breaker Counter
  7. 2. Streaming Top-K & Merging Sorted Iterables
  8. Gotchas & Boundaries
  9. Common Functions

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

Common Functions

Linked from

Related notes