![]() |
VOOZH | about |
heapq.heappushpop() method inserts a new element into a heap and then removes and returns the smallest element. It performs both operations in a single step while maintaining the heap property, making it more efficient than calling heappush() and heappop() separately.
Example: In the code below, we add a new element to the heap and remove the smallest element in a single operation.
2 [4, 5, 6, 8]
Explanation: heapq.heappushpop(h, 5) inserts 5 into the heap and removes the smallest element (2). The removed value is returned and the heap is updated automatically.
heapq.heappushpop(heap, item)
Parameters:
Return Value: Returns the smallest element after performing the push-pop operation.
heapq.heappushpop() first inserts the new element into the heap and then removes the smallest element. The heap is automatically rearranged after the operation to preserve the min-heap property.
Example 1: In the code below, we insert a new number into the heap and remove the smallest element in a single operation.
Removed: 1 Heap: [3, 4, 5, 7]
Explanation: heapq.heappushpop(h, 4) adds 4 and removes the smallest element 1. The heap is then rearranged to maintain the heap property.
Example 2: In the code below, tasks are stored as (priority, task) tuples. Lower priority values are processed first.
Removed: (1, 'Task C') Queue: [(2, 'Task A'), (3, 'Task B')]
Explanation: Since (1, "Task C") is smaller than all existing elements, heappushpop() immediately returns it and leaves the heap unchanged.
Example 3: In the code below, a fixed-size heap is used to keep track of the highest scores.
Removed: 50 Scores: [60, 65, 70]
Explanation: heapq.heappushpop(h, 65) removes the smallest score 50 and inserts 65, helping maintain the top scores in the heap.
Use heapq.heappushpop() when: