heapq
moduleThe heapq
module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides minimum heap implementation where the key of the parent is less than or equal to those of its children. Some of the functions offered by the module are heapify
, heappushpop
, and so on.
Note: Refer What is a Heap? and What is the Python priority queue? to understand more about heaps and priority queues.
merge
methodThe merge
method merges multiple sorted iterables into a single sorted iterable. The method returns an iterator over the sorted result. This method assumes each of the iterables are sorted in ascending order.
heapq.merge(*iterables, key=None, reverse=False)
iterables
refers to the iterables to merge.key
refers to the key function that is used to extract a comparison key from each input element.reverse
is a boolean value. The input elements will be merged with a reverse comparison if this parameter is set to True
.Let’s look at the code below:
import heapqdef merge(iterables):print("heapq.merge(%s) = %s" % (iterables, list(heapq.merge(*iterables))))def merge_key(iterables, lambda_func):print("heapq.merge(%s) = %s" % (iterables, list(heapq.merge(*iterables, key=lambda_func))))lst1 = ['a', 'b', 'd', 'e']lst2 = ['c', 'p', 'q', 'r']merge([lst1, lst2])lst1 = [('a', 1), ('b', 2), ('c', 3)]lst2 = [('p', 15), ('q', 20), ('r', 30)]merge_key([lst1, lst2], lambda x:x[1])
heapq
module.merge
function. It takes the list of iterables as input and prints the sorted merged list of elements in the iterables.merge_key
function. It takes the list of iterables and key function as input and prints the sorted merged list of elements in the iterables according to the given key function.lst1
and lst2
, containing characters.merge
function with lst1
and lst2
. The output is the flattened list of elements from lst1
and lst2
in sorted order.lst1
and lst2
.merge_key
function with lst1
and lst2
and the key function as a lambda expression that returns the second element of the tuple.The output is the flattened list of elements from lst1
and lst2
in sorted order as per the second element of the individual tuples.