VOOZH about

URL: https://www.geeksforgeeks.org/python/python-heapq-heappop-method/

⇱ Python heapq.heappop() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python heapq.heappop() Method

Last Updated : 11 Jun, 2026

heapq.heappop() function removes and returns the smallest element from a heap. After removing the element, the heap is automatically rearranged to maintain the heap property.

Example: The following example removes the smallest element from a heap.


Output
1
[3, 5, 8]

Explanation: heapq.heappop(h) removes and returns the smallest element (1). The remaining elements are rearranged to maintain the heap property.

Syntax

heapq.heappop(heap)

  • Parameters:heap - The heap list from which the smallest element will be removed.
  • Return Value: Returns the smallest element from the heap.

Examples

Example 1: This example creates a heap, removes the smallest element and displays both the removed value and the updated heap.


Output
1
[3, 5, 8]

Explanation: heapq.heappop(h) removes the minimum element from h and returns it. The remaining elements are automatically reorganized into a valid heap.

Example 2: This example stores tasks as (priority, task) tuples and removes the task with the highest priority (lowest priority number).


Output
Task B

Explanation: heapq.heappop(pq) removes the tuple with the smallest priority value. Here, (1, "Task B") is removed first.

Example 3: This example uses negative values to simulate max-heap behavior and removes the largest element.


Output
8
[5, 3, 1]

Explanation: Values are inserted as negatives using heapq.heappush(). -heapq.heappop(h) removes the largest original value and converts it back to a positive number.

Comment
Article Tags:
Article Tags: