A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/heap-queue-or-heapq-in-python/ below:

Heap queue or heapq in Python

Heap queue or heapq in Python

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?
  1. Provides an efficient way to implement priority queues using heaps.
  2. Helps maintain a list in heap order with minimal code and high performance.
  3. Useful in algorithms like Dijkstra's, Huffman encoding or any task requiring quick access to smallest element.
  4. Offers functions like heapify(), heappush() and heappop() for efficient insertion and removal.
  5. Ideal for managing sorted data dynamically without full sorting after each operation.

To use a heap queue in Python, we first need to import the heapq module, use below command in command prompt:

import heapq

heapq.heapify() Function

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)

Output
Heap queue: [15, 20, 25, 30, 40]

Explanation:

Key operations of a heap

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:

Appending and Popping Elements from a Heap Queue

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)

Output
[10, 20, 15, 30, 40]
Smallest: 5
[10, 20, 15, 30, 40]

Explanation:

Appending and Popping Simultaneously

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)

Output
5
[10, 20, 15, 30, 40]

Explanation:

Finding Largest and Smallest Elements in a Heap Queue

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)

Output
3 largest elements: [40, 30, 20]
3 smallest elements: [10, 15, 20]

Note: 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.

Replace and Merge Operations on Heapq

Python’s heapq module provides additional useful operations for heaps like replace and merge.

Replace Operation

heapq.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.

Merge Operation

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)

Output
10
[5, 20, 15, 30, 40]
Merged heap: [2, 4, 5, 6, 8, 20, 15, 30, 40]

Explanation:

Advantages and Disadvantages of Heapq Advantages Disadvantages Fast for adding and removing items with priority. Not good for complex tasks. Uses less memory than some other data types. No direct access to middle items. Simple to use with the 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