Python heapq.merge() Method
Last Updated :
17 Mar, 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))
Output[1, 2, 3, 4, 5, 6, 7, 8]
Explanation:
- The heapq.merge() method merges the two sorted lists list1 and list2 into one sorted list, yielding the output [1, 2, 3, 4, 5, 6, 7, 8].
Syntax of merge() method
heapq.merge(*iterables, key=None, reverse=False)
Parameters
- *iterables: Variable number of sorted iterable objects (e.g., lists, tuples, or other sequences).
- key: An optional function to determine the sort order (similar to sorted()).
- reverse: A boolean flag; if True, the merge happens in descending order (default is False for ascending order).
Return Value
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))
Output[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:
- The method merges three sorted lists into one sorted list, resulting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2. Merging with a Custom Key Function
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))
Output['apple', 'banana', 'kiwi', 'cherry', 'grape', 'mango']
Explanation:
- The key=len argument sorts the strings based on their length. The merged result is sorted by the length of each string.
3. Merging in Reverse Order
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))
Output[2, 4, 6, 8, 1, 3, 5, 7]
Explanation:
- The reverse=True argument causes the merge to happen in descending order, resulting in [8, 7, 6, 5, 4, 3, 2, 1].
When to Use heapq.merge()?
You should use heapq.merge() when:
- Merging Sorted Data: You have multiple already sorted sequences and want to merge them into a single sorted sequence efficiently.
- Efficient Merging: When dealing with large datasets, heapq.merge() is much more efficient than sorting the entire dataset.
- Handling Infinite Sequences: Since heapq.merge() returns an iterator, it is useful when dealing with infinite sequences, as it doesn’t require all the data to be in memory at once.
Similar Reads
Python PIL | Image.merge() method PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files,
1 min read
Python List extend() Method In Python, extend() method is used to add items from one list to the end of another list. This method modifies the original list by appending all items from the given iterable. Using extend() method is easy and efficient way to merge two lists or add multiple elements at once.Letâs look at a simple
2 min read
Python List methods Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, weâll explore all Python list methods with a simple example.List MethodsLet's look at different list methods in Python:append(): Adds an
3 min read
Merge Sort in Python Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorte
4 min read
Merge two sorted arrays in Python using heapq Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge
2 min read