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

Overview

The heapq module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides 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, heappushpop, and more.

Note: Refer to What is a Heap? and What is the Python priority queue? to understand more about heaps and priority queues.

The heappop method

The heappop method pops and returns the smallest element of the given heap. This method removes the smallest element.

To access the smallest element without removing it, we can access the 0th element of the list using list[0].

Syntax

heapq.heappop(heap)
  • heap: This refers to the heap from which the smallest element has to be removed.

Code

import heapq
lst = [28, 2, 32, 22, 10, 1]
print("Original list - ", lst)
heapq.heapify(lst)
print("Heapified list - ", lst)
smallest_item = heapq.heappop(lst)
print("Smallest element - ", smallest_item)
print("List after calling heappop() - ", 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 11: The smallest element is popped by invoking the heappop() method.

Free Resources