all Python 3heapqfunction
heapq.heappushpop()
operations
Push an item and immediately pop the smallest — the reverse order of heapreplace(); if the new item is the smallest, it is returned and the heap is unchanged.
Syntax
heapq.heappushpop(heap, item)
One sift through the tree instead of two, so heappush() followed by heappop() always loses: both are O(log n), but this does half the work. Unlike heapreplace(), it tolerates an empty heap — it simply hands the item back to you. That makes it the standard way to keep a running top-k: hold exactly k items and feed the stream through it.
Examples
import heapq
h = [3, 5, 7]
heapq.heappushpop(h, 1) # → 1 (1 < min, сразу вернули)
heapq.heappushpop(h, 9) # → 3 (вставили 9, извлекли 3)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy