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.
heappop methodThe 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].
heapq.heappop(heap)
heap: This refers to the heap from which the smallest element has to be removed.import heapqlst = [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)
heapq module.lst.lst to a heap using the heapify method.heappop() method.