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 the item has to be inserted.
  • item refers to the element to be inserted.

Code

import heapq
lst = [28, 2, 32, 22, 10, 1]
print("Original list - ", lst)
heapq.heapify(lst)
print("Heapified list - ", lst)
item_to_push = 0
heapq.heappush(lst, item_to_push)
print("List after inserting 0 - ", lst)

Explanation

  • Line 1: We import the heapq module.
  • Line 3: Define a list of integers called lst.
  • Line 7: Convert the lst to a heap using the heapify method.
  • Line 11: The element to be pushed is defined, i.e, item_to_push.
  • Line 13: 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.

Free Resources