Python 3.14+heapqfunction
heapq.heappop_max()
operations
Pops and returns the largest item of a max-heap while keeping the heap invariant. It is the max-heap counterpart of heappop().
Syntax
heapq.heappop_max(heap) -> item
Added in Python 3.14; before that a max-heap was faked by pushing negated numbers (-x) into a regular heap and flipping the sign back on pop, a trick that does not work for strings or objects at all. It only works on a list already turned into a max-heap with heapify_max(): on a plain list it returns heap[0], not the maximum. On an empty heap it raises IndexError, so loops are written as while heap:.
Examples
import heapq
h = [2, 9, 4, 7]
heapq.heapify_max(h)
print([heapq.heappop_max(h) for _ in range(len(h))]) # → [9, 7, 4, 2]
import heapq
try:
heapq.heappop_max([])
except IndexError as e:
print(e) # → index out of range
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy