CKTIS / Python
heapq.heapify
Transforms a list in place into a minimum heap in linear time.
Version: Python 3.14; repository image, production runtime not attested
Syntax
heapq.heapify(heap, /)Transforms a list in place into a minimum heap in linear time.
Only the root is guaranteed to be minimal. Repeated extraction recovers sorted order without assuming a sorted backing list.
Heap construction rearranges the original list in linear time and returns None. Every parent is less than or equal to each of its existing children; equality is allowed. Siblings have no required order. The sample reads the minimum at index zero, then repeatedly removes the root to produce 1, 3, 7, 8.
from heapq import heapify, heappop
h = [9, 1, 8, 3, 3]
assert heapify(h) is None
assert [heappop(h) for _ in range(5)] == [1, 3, 3, 8, 9]
assert heapify(h) is None and h == []
h = [4, 2, 2, 8, 1]
heapify(h)
assert all(h[(i-1)//2] <= h[i] for i in range(1, len(h)))
Examples
import heapq
items = [8, 3, 7, 1]
print(heapq.heapify(items))
print(items[0], [heapq.heappop(items) for _ in range(4)])
Result
None 1 [1, 3, 7, 8]
Heap construction rearranges the original list in linear time and returns None. Every parent is less than or equal to each of its existing children; equality is allowed. Siblings have no required order. The sample reads the minimum at index zero, then repeatedly removes the root to produce 1, 3, 7, 8.