Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

heapq.heappop

Removes and returns the smallest item from a min-heap while repairing the heap.

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

Syntax

heapq.heappop(heap, /)

Removes and returns the smallest item from a min-heap while repairing the heap.

An empty heap raises IndexError. Ordinary list removal from the tail would not implement minimum extraction.

Remove the smallest item under <, which can be a string or another comparable object, from a valid min-heap. The remaining list retains its heap invariant. Each successful call removes one occurrence, including when several priorities tie. Inspect h[0] to peek. The sample consumes 1 and 4, so the third call raises IndexError.

from heapq import heappop
h = [2, 2, 5]
assert h[0] == 2 and len(h) == 3
assert heappop(h) == 2 and len(h) == 2 and h[0] == 2
assert heappop(h) == 2 and heappop(h) == 5
h = ["ant", "dog", "cat"]
assert heappop(h) == "ant" and h[0] == "cat"

Examples

import heapq
heap = [1, 4]
print(heapq.heappop(heap), heapq.heappop(heap))
try:
    heapq.heappop(heap)
except IndexError as error:
    print(type(error).__name__)

Result

1 4
IndexError

Remove the smallest item under <, which can be a string or another comparable object, from a valid min-heap. The remaining list retains its heap invariant. Each successful call removes one occurrence, including when several priorities tie. Inspect h[0] to peek. The sample consumes 1 and 4, so the third call raises IndexError.

Sources