heapq · Python
heappop
Removes and returns the smallest item.
heapq.heappop(heap, /)
Complexity
| Worst case | O(log n) |
|---|---|
| Extra space | O(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
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.