The heapq
module is an inbuilt module in python. The module offers APIs for different operations of the heap data structure. Also, it provides min heap implementation where the parent key is less than or equal to those of its children. Some of the functions offered by the module are heapify
, heappushpop
etc.
heappush
methodThe heappush
method inserts the given item onto the heap.
heapq.heappush(heap, item)
heap
: This key refers to the heap to which the item
has to be inserted.item
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)item_to_push = 0heapq.heappush(lst, item_to_push)print("List after inserting 0 - ", lst)
heapq
module.lst
.lst
to a heap using the heapify
method.item_to_push
.item_to_push
is inserted to lst
using heappush()
method.We can observe that after we insert 0
to the heap, the new smallest element (i.e. 0th
index element) is 0
in the output.