heapq.heapify, heapq.heappush, heapq.heappop, heapq.nsmallest, heapq.nlargest, heapq.merge
heapq.heapify(heap)
heapq.heappush(heap, item)
heapq.heappop(heap)
heapq.nsmallest(n, iterable, key=None)
heapq.nlargest(n, iterable, key=None)
heapq.merge(*iterables, key=None, reverse=False)Turn a list into a min-heap, push and pop the smallest item, or take the n smallest or largest values from an iterable.
| Parameter | Description |
|---|---|
heap | A list that already is, or will become, a heap. heapify mutates it in place. |
item / n / iterable | heappush inserts item. nsmallest and nlargest take a count and any iterable. merge takes pre-sorted iterables. |
Returns: heapify, heappush, and heappop operate on the list; heappop returns the smallest item. nsmallest and nlargest return lists. merge returns an iterator.
- The heap lists below are the exact shapes measured on Python 3.13.12 after heapify, heappush(0), and heappop. Other valid heap layouts are possible in general; these are the results of this implementation for these inputs.
- Print the list after heappush in a separate statement from heappop. Passing the same list to print along with heappop can show the post-pop list for both arguments.
import heapq
heap = [5, 1, 4, 2]
heapq.heapify(heap)
print(heap, heap[0])
heapq.heappush(heap, 0)
print(heap)
print(heapq.heappop(heap))
print(heap)
print(heapq.nsmallest(3, [5, 1, 4, 2, 8]), heapq.nlargest(2, [5, 1, 4, 2, 8]))
print(list(heapq.merge([1, 4], [2, 3, 8])))Expected output
[1, 2, 4, 5] 1
[0, 1, 4, 5, 2]
0
[1, 2, 4, 5]
[1, 2, 4] [8, 5]
[1, 2, 3, 4, 8]