Python heapq.merge() Method Last Updated : 17 Mar, 2025 Comments Improve Suggest changes Like Article Like Report 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() methodheapq.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 ValueThe 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() method1. 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 FunctionYou 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 OrderIf 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. Comment More infoAdvertise with us Next Article Python heapq.merge() Method B brijkan3mz4 Follow Improve Article Tags : Python Python-DSA Practice Tags : python 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 heapq.heapify() Method The heapq.heapify() function in Python is used to transform a regular list into a valid min-heap. A min-heap is a binary tree where the smallest element is always at the root. This method is highly useful when you need to create a heap structure from an unordered list and maintain the heap property 4 min read Python __add__() magic method Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2 1 min read Python List append() Method append() method in Python is used to add a single item to the end of list. This method modifies the original list and does not return a new list. Let's look at an example to better understand this.Pythona = [2, 5, 6, 7] # Use append() to add the element 8 to the end of the list a.append(8) print(a)O 3 min read Set add() Method in Python The set.add() method in Python adds a new element to a set while ensuring uniqueness. It prevents duplicates automatically and only allows immutable types like numbers, strings, or tuples. If the element already exists, the set remains unchanged, while mutable types like lists or dictionaries cannot 4 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 Python | Decimal logical_and() method Decimal#logical_and() : logical_and() is a Decimal class method which returns the digit-wise and of the two (logical) Decimal values. Syntax: Decimal.logical_and() Parameter: Decimal values Return: the digit-wise and of the two (logical) Decimal values. Code #1 : Example for logical_and() method Pyt 2 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 Python | Numpy np.ma.concatenate() method With the help of np.ma.concatenate() method, we can concatenate two arrays with the help of np.ma.concatenate() method. Syntax : np.ma.concatenate([list1, list2]) Return : Return the array after concatenation. Example #1 : In this example we can see that by using np.ma.concatenate() method, we are a 1 min read Like