Python Glossary Русский

all Python 3heapqfunction

heapq.heapify()

operations

Turns an arbitrary list into a min-heap in O(n). It rearranges the list in place.

Syntax

heapq.heapify(x)

Building the heap in one shot is cheaper than filling it item by item: heapify is O(n), whereas n heappush calls cost O(n log n). The classic misread is assuming the list comes out sorted — it is only partially ordered, the guarantee is x[0] being the minimum, and printing the list looks shuffled. There is no max-heap in heapq; the usual workaround is storing negated values.

Examples

import heapq
data = [5, 2, 8, 1, 4]
heapq.heapify(data)
data[0] # → 1  (минимальный элемент)
heapq.heappop(data) # → 1
heapq.heappop(data) # → 2
data # → [4, 5, 8]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy