What is heapq.heappush() in Python?
Overview
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 method
The heappush method inserts the given item onto the heap.
Syntax
heapq.heappush(heap, item)
heap: This key refers to the heap to which theitemhas to be inserted.itemrefers to the element to be inserted.
Code
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)
Explanation
- Line 1: We import the
heapqmodule. - Line 3: Define a list of integers called
lst. - Line 7: Convert the
lstto a heap using theheapifymethod. - Line 11: The element to be pushed is defined, i.e,
item_to_push. - Line 13:
item_to_pushis inserted tolstusingheappush()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.