Python Glossary Русский

all Python 3heapqfunction

heapq.heappop()

operations

Pop and return the smallest item from the heap, preserving the invariant; raises IndexError on an empty heap. O(log n).

Syntax

heapq.heappop(heap)

An empty heap raises IndexError rather than returning None, so guard with if heap: or catch it. To peek at the minimum without removing it, just read heap[0] — indexing rebuilds nothing and costs O(1). Draining everything with heappop does yield sorted order, but for a list you already have, sorted() is simpler and faster; heapq pays off when pushes and pops interleave.

Examples

import heapq
h = [1, 2, 3]
heapq.heappop(h) # → 1
heapq.heappop(h) # → 2
h # → [3]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy