heappushpop function of heapq module in python

The heappushpop() function from the Python heapq module first inserts an item into the min heap and returns the root node(i.e., the element with the lowest value) of the min heap after removing it.

Heapq Updated 8 Jan 2020 1 min read

Overview

  • The function heappushpop() of the heapq module in Python removes and returns the smallest element (i.e., the root node) from a min heap after an item is pushed into the heap.
  • The heap property is maintained all the time.

Example

python
# Example Python program that pushes an element

# and pops the minimum element using the function heapq.heappushpop()

import heapq

# Create a min heap

elements = [97, 83, 89, 71, 79, 73]

heapq.heapify(elements)

print("Min heap:")

print(elements)

# Push an element and do a pop

e1 = heapq.heappushpop(elements, 103)

print("Heap after pushing an item and popping the minimum:")

print(elements)

# Push another element and do a pop

print("Heap after pushing another item and popping the minimum:")

heapq.heappushpop(elements, 101)

print(elements)

Output

Output
Min heap:

[71, 79, 73, 83, 97, 89]

Heap after pushing an item and popping the minimum:

[73, 79, 89, 83, 97, 103]

Heap after pushing another item and popping the minimum:

[79, 83, 89, 101, 97, 103]