Heappush Function Of Heapq Module In Python

Overview:

  • A min heap is a binary tree in which the parent nodes hold smaller values than that of the children.  
  • As new elements get added into the heap, the “heap” property stated above is maintained.
  • The heapq module in Python provides a set of functions to create and manipulate min heaps.
  • The heappush() method pushes an element into an existing heap in such a way that the heap property is maintained.

Example:

The Python example constructs a min heap through heapify() function and subsequently calls heappush() twice to add two elements into the heap, while maintaining the heap property.

# Example Python program that pushes elements into a heap

# while maintaining the heap property

import heapq

 

# Data as a Python list

heapData        = [10, 50, 60, 20, 70]

 

# Make the Python list into a heap

heapq.heapify(heapData)

print("Heap:")

 

# Print the heap

print(heapData)

 

# Push new elements into the heap

heapq.heappush(heapData, 40)

print(heapData)

 

heapq.heappush(heapData, 30)

print(heapData)

 

Output:

Heap:

[10, 20, 60, 50, 70]

[10, 20, 40, 50, 70, 60]

[10, 20, 30, 50, 70, 60, 40]

 

Initial Heap before calling heappush()

After adding an element 40 into the heap using heapq.heappush()

After adding another element 30 into the heap using heappush()


Copyright 2022 © pythontic.com