Python Glossary Русский

Python 3.14+heapqfunction

heapq.heapreplace_max()

operations

Pops the largest item of a max-heap and pushes a new one in a single pass, so the heap keeps its size.

Syntax

heapq.heapreplace_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 pop first, then push: the old root is returned even if the new item is larger. On an empty heap it raises IndexError. When you need the maximum of the old items and the new one, use heappushpop_max().

Examples

import heapq
h = [5, 3]
print(heapq.heapreplace_max(h, 9), h)  # → 5 [9, 3]
import heapq
try:
    heapq.heapreplace_max([], 1)
except IndexError as e:
    print(e)  # → index out of range

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy