Python Glossary Русский

all Python 3heapqfunction

heapq.heapreplace()

operations

Pop the smallest item and push a new one in a single pass — more efficient than heappop() followed by heappush(). Pops first, then pushes.

Syntax

heapq.heapreplace(heap, item)

On an empty heap it raises IndexError: the pop comes first and there is nothing to pop. The value returned can be larger than the one you pushed, so in a top-k loop guard it with if item > heap[0]; without that guard use heappushpop() instead. The heap size never changes, which is exactly why this fits fixed-size buffers.

Examples

import heapq
h = [1, 3, 5]
heapq.heapreplace(h, 4) # → 1  (извлекли 1, вставили 4)
h # → [3, 4, 5]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy