heapq#

Python’s built-in module for min-heap operations on a standard list.

Basic Usage#

import heapq

h = []
heapq.heappush(h, 3)
heapq.heappush(h, 1)
heapq.heappush(h, 5)

print(heapq.heappop(h)) # 1 (Smallest element first)

Heapify a list#

nums = [3, 1, 5]
heapq.heapify(nums) # In-place transformation
print(nums[0]) # 1

Max-Heap Tip#

To implement a max-heap, negate the values before pushing and negate them again after popping.

h = []
heapq.heappush(h, -5)
heapq.heappush(h, -10)

print(-heapq.heappop(h)) # 10

Tuple Priority and Tie-Breaking#

When pushing (priority, obj) tuples where obj does not support < comparison, equal priorities trigger TypeError when Python compares the next tuple element. Insert a monotonically increasing idx as a tie-breaker.

eg.

pq = []
heapq.heappush(pq, (dist, idx, node))

nlargest / nsmallest#

heapq.nlargest(n: int, iterable: Iterable[T], key: Callable[[T], Any] | None = None) -> list[T]
heapq.nsmallest(n: int, iterable: Iterable[T], key: Callable[[T], Any] | None = None) -> list[T]

Returns the same result as sorted(iterable, key=key, reverse=True)[:n] (nsmallest in ascending order). Non-mutating, and accepts any iterable directly, including generators and streams.

  • Maintains a size-n heap internally: O(N log n) time, O(n) space (N = input size)
  • Returns [] for n <= 0, and all elements sorted when n >= len(iterable)
  • Prefer max()/min() for n == 1, and sorted() when n is close to N

eg.

heapq.nlargest(2, [3, 1, 5, 2])                       # [5, 3]
heapq.nsmallest(2, [3, 1, 5, 2])                      # [1, 2]
heapq.nlargest(2, [[0], [1, 2, 3], [4, 5]], key=len)  # [[1, 2, 3], [4, 5]]