all Python 3heapqfunction
heapq.heappush()
operations
Push an item onto the heap, preserving the heap invariant; the heap is a plain list whose smallest item is always heap[0]. O(log n).
Syntax
heapq.heappush(heap, item)
Because the heap is an ordinary list, nothing stops you from corrupting it: an append(), insert() or direct assignment that bypasses heapq makes every later heappop meaningless. Priority queues usually push (priority, item) tuples, but on equal priorities Python falls through to comparing the items themselves and blows up with TypeError on non-comparable objects — inserting a monotonically increasing counter as the second field fixes it. When a pop follows immediately, heappushpop does both with a single reordering.
Examples
import heapq
h = []
heapq.heappush(h, 3)
heapq.heappush(h, 1)
heapq.heappush(h, 2)
h[0] # → 1 (минимум всегда первый)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy