What is the heapq.heappushpop() method in Python?

The heapq module

The heapq module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides a min-heap implementation where the key of the parent is less than or equal to those of its children. Some of the functions offered by the module are heapify and heappushpop, among others.

Note: To understand more about heaps and priority queues, please refer to What is a Heap? and What is the Python priority queue?

The heappushpop method

The heappushpop method inserts a given item to the heap and then pops the smallest element from the heap. This method is equivalent to heappush() followed by heappop().

Syntax

heapq.heappushpop(heap, item)
  • heap: This refers to the heap in which the item has to be inserted.
  • item: This refers to the element to be inserted.

Example

import heapq
lst = [28, 2, 32, 22, 10, 1]
print("Original list - ", lst)
heapq.heapify(lst)
print("Heapified list - ", lst)
print("Calling heapreplace() ----")
pop_item = heapq.heappushpop(lst, 0)
print("The popped item - ", pop_item)
print("List after heapreplace call - ", lst)

Explanation

  • Line 1: We import the heapq module.
  • Line 3: We define a list of integers called lst.
  • Line 7: We convert the lst to a heap using the heapify method.
  • Line 9: We print the heapified list.
  • Line 11: We invoke the heappushpop() method where we add zero to lst and store the popped element in pop_item.

In the output, we get zero as the popped item because once we insert zero to lst, the elements in the heap are rearranged. Now, zero becomes the smallest element, and when the smallest element is popped, zero is returned.

Free Resources