Last Updated : 02 Aug, 2025
A heap queue or priority queue is a data structure that allow to quickly access the smallest (min-heap) or largest (max-heap) element. In Python, heaps are usually implemented as min-heaps which means the smallest element is always at the root of the tree, making it easy to access.
Why do we need Heap queue?To use a heap queue in Python, we first need to import the heapq module, use below command in command prompt:
heapq.heapify() Functionimport heapq
Converts a regular list into a min-heap in-place, where the smallest element becomes the root (first element of the list).
heapq.heapify(x)
Parameter: x list to be converted into a heap.
Example of creating a heap queue:
Python
import heapq
# Creating a list
li = [25, 20, 15, 30, 40]
# Convert the list into a heap
heapq.heapify(li)
print("Heap queue:", li)
Heap queue: [15, 20, 25, 30, 40]
Explanation:
Heaps support several essential operations that help manage data efficiently while maintaining heap property. These operations are crucial in scenarios like priority queues, scheduling and graph algorithms. Operations are:
In a heap queue, you can efficiently insert and remove elements while maintaining the heap property.
These operations ensure the heap remains properly ordered at all times.
Example: This code demonstrates how to create a heap, append an element, and remove the smallest element using the heapq module.
Python
import heapq
# Creating an initial heap
h = [10, 20, 15, 30, 40]
heapq.heapify(h)
# Appending an element
heapq.heappush(h, 5)
# Heap before popping
print(h)
# Pop the smallest element from the heap
min = heapq.heappop(h)
print("Smallest:", min)
print(h)
[10, 20, 15, 30, 40] Smallest: 5 [10, 20, 15, 30, 40]
Explanation:
heapq.heappushpop() function efficiently pushes a new element onto the heap and pops the smallest one in a single step. This is faster than doing heappush() followed by heappop() separately, as it maintains the heap structure with just one adjustment. It takes two arguments: the heap and the element to be pushed.
Example: Pushes 5 onto the heap and pops the smallest element in a single step using heappushpop().
Python
import heapq
# Creating a heap
h = [10, 20, 15, 30, 40]
heapq.heapify(h)
# Push a new element (5) and pop the smallest element at the same time
min = heapq.heappushpop(h, 5)
print(min)
print(h)
5 [10, 20, 15, 30, 40]
Explanation:
Although a heap allows for efficient access to smallest element, it doesn’t directly support finding largest element. However, heapq module provides two handy functions nlargest() and nsmallest() to retrieve largest and smallest elements from the heap, respectively.
nlargest() and nsmallest()These functions allow us to easily find n largest or n smallest elements in a heap. They do this by efficiently scanning heap and sorting the required number of elements.
Example: Finding the largest and smallest elements using nlargest() and nsmallest()
Python
import heapq
# Creating a heap
h = [10, 20, 15, 30, 40]
heapq.heapify(h)
# Find the 3 largest elements
maxi = heapq.nlargest(3, h)
print("3 largest elements:", maxi)
# Find the 3 smallest elements
min = heapq.nsmallest(3, h)
print("3 smallest elements:", min)
3 largest elements: [40, 30, 20] 3 smallest elements: [10, 15, 20]
Replace and Merge Operations on HeapqNote: The heapq module allows in-place heap operations on lists, making it an efficient and simple way to implement priority queues and similar structures in Python.
Python’s heapq module provides additional useful operations for heaps like replace and merge.
Replace Operationheapq.heapreplace() function is a combination of pop and push. It pops smallest element from the heap and inserts a new element into the heap, maintaining the heap property. This operation is useful when we want to replace the smallest element with a new value in a heap.
heapq.merge() function is used to merge multiple sorted iterables into a single sorted heap. It returns an iterator over the sorted values, which we can then iterate through.
This operation is efficient because it avoids sorting the elements from scratch. Instead, it merges already-sorted iterables in a way that maintains the heap property.
Example of replace and merge operations:
Python
import heapq
# Creating a heap
h1 = [10, 20, 15, 30, 40]
heapq.heapify(h1)
# Replacing the smallest element (10) with 5
min = heapq.heapreplace(h1, 5)
print(min)
print(h1)
# Merging Heaps
h2 = [2, 4, 6, 8]
# Merging the lists
h3 = list(heapq.merge(h1, h2))
print("Merged heap:", h3)
10 [5, 20, 15, 30, 40] Merged heap: [2, 4, 5, 6, 8, 20, 15, 30, 40]
Explanation:
heapq
module. Can’t fully sort the items automatically. Works in many cases like heaps and priority queues. Not safe with multiple threads at the same time.
Heap queue (or heapq) in Python
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4