Heappushpop Function Of Heapq Module In Python

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:

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

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]

 


Copyright 2023 © pythontic.com