Last Updated : 23 Jul, 2025
The heapq.merge() method in Python is part of the heapq module, which is used for heap-related operations. This method allows you to merge multiple sorted input iterables into a single sorted output iterable, efficiently using the heap data structure. It is particularly useful when working with sorted data and helps in merging sorted sequences without needing to sort the entire data again.
Example: Merging Two Sorted Lists
Python
import heapq
# Two sorted lists
a = [1, 3, 5, 7]
b = [2, 4, 6, 8]
# Merge the lists
merged = heapq.merge(a, b)
print(list(merged))
[1, 2, 3, 4, 5, 6, 7, 8]
Explanation:
Parametersheapq.merge(*iterables, key=None, reverse=False)
The method returns an iterator that yields the elements from the sorted sequences in ascending order by default (or descending if reverse=True), combining the elements of all input iterables.
Examples of merge() method 1. Merging Multiple Sorted Iterables Python
import heapq
# Three sorted lists
a = [1, 3, 5, 7]
b = [2, 4, 6, 8]
c = [0, 9, 10]
# Merge the lists
merged = heapq.merge(a, b, c)
print(list(merged))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:
You can use the key parameter to customize the sorting of the elements. For example, sorting strings by their length.
Python
import heapq
# Two lists of strings
a = ["apple", "banana", "kiwi"]
b = ["cherry", "grape", "mango"]
# Merge the lists by string length
merged = heapq.merge(a, b, key=len)
print(list(merged))
['apple', 'banana', 'kiwi', 'cherry', 'grape', 'mango']
Explanation:
If you want to merge the iterables in descending order, you can use the reverse parameter.
Python
import heapq
# Two sorted lists
a = [1, 3, 5, 7]
b = [2, 4, 6, 8]
# Merge the lists in reverse (descending) order
merged = heapq.merge(a, b, reverse=True)
print(list(merged))
[2, 4, 6, 8, 1, 3, 5, 7]
Explanation:
You should use heapq.merge() when:
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