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.
import heapq
h = [5, 1, 8, 3]
heapq.heapify(h)
print(heapq.heappop(h))
print(h)
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.
import heapq
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, x)
v = heapq.heappop(h)
print(v)
print(h)
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).
import heapq
pq = []
heapq.heappush(pq, (2, "Task A"))
heapq.heappush(pq, (1, "Task B"))
heapq.heappush(pq, (3, "Task C"))
p, t = heapq.heappop(pq)
print(t)
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.
import heapq
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, -x)
v = -heapq.heappop(h)
print(v)
print([-x for x in h])
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.