heappush function of heapq module in Python

The heappush() function from the heapq module of Python adds an element into an existing heap while maintaining the heap property. The Python example creates a heap, adds elements to it and prints the heap.

Heapq Updated 24 Dec 2019 1 min read

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.

python
# 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

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()