![]() |
VOOZH | about |
heapq.heapreplace() function removes and returns the smallest element from a heap and inserts a new element into the heap in a single operation. This is useful when you need to replace the smallest item while maintaining the heap property.
Example: The following example replaces the smallest element in a heap with a new value.
3 [4, 5, 7, 10]
Explanation: heapq.heapreplace(h, 4) removes the smallest element (3), inserts 4, and rearranges the heap to maintain the heap property.
heapq.heapreplace(heap, item)
Parameters:
Return Value: Returns the smallest element that was removed from the heap.
heapq.heapreplace() combines two operations into one:
This operation is more efficient than calling heappop() and heappush() separately.
Example 1: This example removes the smallest element from the heap and replaces it with a new value. The heap is updated automatically after the operation.
2 [5, 6, 8, 12]
Explanation: heapq.heapreplace(h, 5) removes the smallest value (2) and inserts 5 while keeping h as a valid heap.
Example 2: This example keeps only the top 3 largest scores by replacing the smallest score whenever a better score arrives.
[60, 65, 70]
Explanation: heapq.heapreplace(h, new_score) replaces the smallest score (50) with 65, allowing the heap to keep only the top 3 scores.
Example 3: This example updates the highest-priority task by replacing the current smallest-priority entry with a new one.
(1, 'Task A') [(0, 'Urgent Task'), (3, 'Task C'), (2, 'Task B')]
Explanation: heapq.heapreplace(pq, (0, "Urgent Task")) removes the current smallest-priority item and inserts the new task with priority 0.
Use heapq.heapreplace() when:
Both operations replace the smallest element, but heapreplace() performs the replacement in a single step and is more efficient.
smallest = heapq.heappop(heap)
heapq.heappush(heap, item)
The above code performs two heap operations, whereas heapreplace() does the same task in one operation.
If item is smaller than the current smallest element, heappushpop() may immediately return item, while heapreplace() always replaces an existing heap element.