![]() |
VOOZH | about |
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.
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.
heapq.heappop(heap)
Example 1: This example creates a heap, removes the smallest element and displays both the removed value and the updated heap.
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).
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.
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.