Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

heapq.heapreplace

Removes the existing minimum from a nonempty heap and replaces it with the new item.

Version: Python 3.14; repository image, production runtime not attested

Syntax

heapq.heapreplace(heap, item, /)

Removes the existing minimum from a nonempty heap and replaces it with the new item.

The returned value can exceed the incoming item because removal always targets the previous heap.

Remove the old root before retaining the new item. This is useful when a fixed-size queue must accept the replacement regardless of its priority. In [4, 8], inserting 2 returns 4 and leaves 2 as the minimum at length two. With no old root an empty list raises IndexError.

from heapq import heapreplace
h = [4]
assert heapreplace(h, -1) == 4 and h == [-1]
try:
    heapreplace([], 7)
except IndexError:
    pass
else:
    raise AssertionError

Examples

import heapq
heap = [4, 8]
print(heapq.heapreplace(heap, 2))
print(heap[0], len(heap))

Result

4
2 2

Remove the old root before retaining the new item. This is useful when a fixed-size queue must accept the replacement regardless of its priority. In [4, 8], inserting 2 returns 4 and leaves 2 as the minimum at length two. With no old root an empty list raises IndexError.

Sources