heapq · Python

heappop

Removes and returns the smallest item.

heapq.heappop(heap, /)

Complexity

Worst caseO(log n)
Extra spaceO(1)

Move the last item to the root and sift it down to a leaf, then up (CPython's variant does fewer comparisons on average).

Tested example

heap = [3, 1, 2]
heapq.heapify(heap)
assert heapq.heappop(heap) == 1
assert heapq.heappop(heap) == 2
heapq.heappop(heap)
try:
    heapq.heappop(heap)
    raise AssertionError("expected IndexError")
except IndexError:
    pass
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_heapq.py

Parameters

heap
A list in heap order.

Behaviour

Returns
The smallest item.
Errors and preconditions
IndexError if the heap is empty.
Changes
The list shrinks by 1.
Memory and invalidation
No allocation.