Python heapq Module
Example
Maintain a min-heap and pop the smallest items:
import heapq
h = []
heapq.heappush(h, 3)
heapq.heappush(h, 1)
heapq.heappush(h, 2)
print([heapq.heappop(h) for _ in range(3)])
Try it Yourself »
Definition and Usage
The heapq module provides heap (priority queue) algorithms on regular Python lists.
Use it to push/pop the smallest item efficiently and to implement priority-based workflows.
Members
| Member | Description |
|---|---|
| heapify() | Transform list into a heap, in-place, in linear time. |
| heappop() | Pop and return the smallest item from the heap. |
| heappush() | Push item onto heap while maintaining the heap invariant. |
| heappushpop() | Push item on the heap, then pop and return the smallest item (more efficient than separate calls). |
| heapreplace() | Pop and return smallest item, and then push the new item. |
| merge() | Merge multiple sorted iterables into a single sorted iterator. |
| nlargest() | Return a list with the n largest elements. |
| nsmallest() | Return a list with the n smallest elements. |