Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
heap

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
communitycreator
heap

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring