heapq.heapify() vs heapq.heappush()
heapq.heapify() and heapq.heappush() are both Python Heapq Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. heapq.heapify(): Transforms a list into a heap (min-heap), in-place, O(n) time. Its syntax is heapq.heapify(x), and it returns none heapq.heappush(): Pushes an item onto the heap, maintaining the heap invariant. Its syntax is heapq.heappush(heap, item), and it returns none Example of heapq.heapify(): import heapq
h = [3, 1, 4, 1, 5, 9]
heapq.heapify(h)
# h = [1, 1, 4, 3, 5, 9] (heap property). Example of heapq.heappush(): h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappush(h, 3)
# h = [1, 5, 3]. Read the full references for heapq.heapify() and heapq.heappush() to see parameters, edge cases, and example code side by side. Other Heapq Module APIs worth comparing: heapq.heappop(), heapq.heappushpop(), heapq.heapreplace(), heapq.nlargest(), heapq.nsmallest().