heapq
moduleThe heapq
module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides a min-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
and heappushpop
, among others.
Note: To understand more about heaps and priority queues, please refer to What is a Heap? and What is the Python priority queue?
heappushpop
methodThe heappushpop
method inserts a given item to the heap and then pops the smallest element from the heap. This method is equivalent to heappush() followed by heappop().
heapq.heappushpop(heap, item)
heap
: This refers to the heap in which the item
has to be inserted.item
: This refers to the element to be inserted.import heapqlst = [28, 2, 32, 22, 10, 1]print("Original list - ", lst)heapq.heapify(lst)print("Heapified list - ", lst)print("Calling heapreplace() ----")pop_item = heapq.heappushpop(lst, 0)print("The popped item - ", pop_item)print("List after heapreplace call - ", lst)
heapq
module.lst
.lst
to a heap using the heapify
method.heappushpop()
method where we add zero to lst
and store the popped element in pop_item
.In the output, we get zero as the popped item because once we insert zero to lst
, the elements in the heap are rearranged. Now, zero becomes the smallest element, and when the smallest element is popped, zero is returned.