VOOZH about

URL: https://www.geeksforgeeks.org/python/python-heapq-merge-method/

⇱ Python heapq.merge() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python heapq.merge() Method

Last Updated : 15 Jun, 2026

heapq.merge() method merges multiple already sorted iterables into a single sorted iterator. It does not modify the original data and returns elements in sorted order without creating a fully sorted list in advance.

Example: The following example merges two sorted lists into a single sorted sequence.


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

Explanation: heapq.merge(a, b) combines the sorted lists and returns their elements in sorted order.

Syntax

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

Parameters:

  • *iterables: One or more sorted iterables to merge.
  • key (optional): Function used for custom comparison.
  • reverse (optional): If True, merges iterables in descending order.

Return Value: Returns an iterator containing the merged elements in sorted order.

Working of heapq.merge()

heapq.merge() takes multiple sorted iterables and returns their elements one by one in sorted order. It uses a heap internally to efficiently determine the next smallest (or largest) element to return.

Time Complexity: O(n log k) Where,

  • n = total number of elements
  • k = number of iterables being merged

Example 1: This example merges three sorted lists into a single sorted sequence. The resulting iterator contains all elements in ascending order.


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

Explanation: heapq.merge(a, b, c) merges all three sorted lists while preserving sorted order.

Example 2: This example merges two sorted lists of strings based on their lengths. The key parameter controls how elements are compared.


Output
['a', 'hi', 'cat', 'tiger', 'giraffe', 'elephant']

Explanation: key=len compares strings using their lengths, so elements are merged according to string size.

Example 3: This example merges two lists that are already sorted in descending order.


Output
[9, 8, 7, 6, 5, 4]

Explanation: reverse=True merges the iterables assuming they are already sorted in descending order.

When to Use heapq.merge()

Use heapq.merge() when:

  • You need to combine multiple sorted sequences into one sorted sequence.
  • The datasets are large and you want an efficient alternative to concatenating and sorting.
  • You want to process merged data lazily using an iterator instead of creating a complete list in memory.
Comment
Article Tags:
Article Tags: