Python Glossary Русский

Python 3.14+heapqfunction

heapq.heappushpop_max()

operations

Pushes an item onto a max-heap and then pops the largest one, faster than separate heappush_max() and heappop_max() calls.

Syntax

heapq.heappushpop_max(heap, item) -> item

Added in Python 3.14; before that a max-heap was faked by pushing negated numbers (-x) into a regular heap and flipping the sign back on pop, a trick that does not work for strings or objects at all. The order is push first, then pop: if the new item is larger than the root, that same item comes back and the heap is untouched. That is the difference from heapreplace_max(), which pops the old root first and so may return something smaller than the new item.

Examples

import heapq
h = [5, 3]
print(heapq.heappushpop_max(h, 9), h)  # → 9 [5, 3]
print(heapq.heappushpop_max(h, 1), h)  # → 5 [3, 1]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy