heapq.heappush() vs heapq.heappop()
heapq.heappush() and heapq.heappop() 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.heappush(): Pushes an item onto the heap, maintaining the heap invariant. Its syntax is heapq.heappush(heap, item), and it returns none heapq.heappop(): Pops and returns the smallest item from the heap. Its syntax is heapq.heappop(heap), and it returns smallest item Example of heapq.heappush(): h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappush(h, 3)
# h = [1, 5, 3]. Example of heapq.heappop(): h = [1, 3, 5, 7]
heapq.heappop(h) # 1
heapq.heappop(h) # 3. Read the full references for heapq.heappush() and heapq.heappop() to see parameters, edge cases, and example code side by side. Other Heapq Module APIs worth comparing: heapq.heapify(), heapq.heappushpop(), heapq.heapreplace(), heapq.nlargest(), heapq.nsmallest(). Both belong to the Heapq Module category in the Python Reference documentation.