CKTIS / Python
Module heapq
Maintain a binary heap in a list for priority-queue operations.
Version: Python 3.14; repository image, production runtime not attested
Syntax
heapq.heapify(items)Maintain a binary heap in a list for priority-queue operations.
A min-heap places its least element at index zero without sorting the rest of the list. Python 3.14 also provides explicit max-heap operations ending in _max.
Repeated pops yield priority order and popping an empty heap raises IndexError.
Examples
import heapq
lo = [4, 1, 3, 2]
hi = lo.copy()
heapq.heapify(lo)
heapq.heapify_max(hi)
print([heapq.heappop(lo) for _ in range(4)])
print(heapq.heappop_max(hi))
try:
heapq.heappop(lo)
except IndexError:
print("empty heap")
Result
[1, 2, 3, 4] 4 empty heap
Repeated pops yield priority order and popping an empty heap raises IndexError.