![]() |
VOOZH | about |
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.
[1, 2, 3, 4, 5, 6]
Explanation: heapq.merge(a, b) combines the sorted lists and returns their elements in sorted order.
heapq.merge(*iterables, key=None, reverse=False)
Parameters:
Return Value: Returns an iterator containing the merged elements in sorted order.
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,
Example 1: This example merges three sorted lists into a single sorted sequence. The resulting iterator contains all elements in ascending order.
[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.
['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.
[9, 8, 7, 6, 5, 4]
Explanation: reverse=True merges the iterables assuming they are already sorted in descending order.
Use heapq.merge() when: