heapq
The Python heapq
module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
This module offers an efficient way to maintain a list in which you want to repeatedly access the smallest item without sorting the entire list.
Here’s a quick example:
>>> import heapq
>>> nums = [5, 1, 3, 7, 8, 2]
>>> heapq.heapify(nums)
>>> heapq.heappop(nums)
1
>>> heapq.heappop(nums)
2
>>> heapq.heappop(nums)
3
Key Features
- Provides an efficient implementation of the heap queue algorithm
- Allows maintaining a list as a heap
- Supports finding and popping the smallest item
- Offers functions to push and pop items while maintaining heap order
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
heapq.heappush() |
Function | Pushes an item onto the heap, maintaining order |
heapq.heappop() |
Function | Pops the smallest item off the heap |
heapq.heapify() |
Function | Transforms a list into a heap, in-place |
heapq.nlargest() |
Function | Finds the n largest elements from a dataset |
heapq.nsmallest() |
Function | Finds the n smallest elements from a dataset |
Examples
Transforming a list into a heap:
>>> import heapq
>>> nums = [5, 1, 3, 7, 8, 2]
>>> heapq.heapify(nums)
>>> nums
[1, 5, 2, 7, 8, 3]
Pushing a new item onto the heap:
>>> heapq.heappush(nums, 4)
>>> nums
[1, 4, 2, 7, 8, 3, 5]
Popping the smallest item off the heap:
>>> heapq.heappop(nums)
1
Common Use Cases
- Implementing priority queues
- Scheduling tasks based on priority
- Finding the smallest or largest elements in a collection
Real-World Example
Suppose you need to process tasks based on priority. You can use a heap to manage the tasks efficiently:
>>> import heapq
>>> tasks = [(3, "write code"), (1, "write specs"), (2, "test code")]
>>> heapq.heapify(tasks)
>>> while tasks:
... priority, task = heapq.heappop(tasks)
... print(f"Processing task: {task} with priority {priority}")
...
Processing task: write specs with priority 1
Processing task: test code with priority 2
Processing task: write code with priority 3
In this example, you use the heapq
module to manage tasks by their priority, ensuring that tasks are processed in the correct order.
Related Resources
Tutorial
The Python heapq Module: Using Heaps and Priority Queues
In this step-by-step tutorial, you'll explore the heap and priority queue data structures. You'll learn what kinds of problems heaps and priority queues are useful for and how you can use the Python heapq module to solve them.
By Leodanis Pozo Ramos • Updated July 9, 2025