A RetroSearch Logo

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

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-heapq-merge-method/ below:

Python heapq.merge() Method - GeeksforGeeks

Python heapq.merge() Method

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))

Output
[1, 2, 3, 4, 5, 6, 7, 8]

Explanation:

Syntax of merge() method

heapq.merge(*iterables, key=None, reverse=False)

Parameters 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:

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:

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:

When to Use heapq.merge()?

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