heapq · Python

heappush

Appends an item and sifts it up to restore the heap order.

heapq.heappush(heap, item, /)

Complexity

Best caseO(1)
AmortizedO(log n) (the list append is amortized O(1))
Worst caseO(log n)
Extra spaceO(1) amortized

Append at the end, then swap with the parent while the parent is larger: at most the height of the tree, ⌊log₂ n⌋ swaps.

Tested example

tasks: list[tuple[int, str]] = []  # heapq works on a plain list
heapq.heappush(tasks, (2, "write tests"))
heapq.heappush(tasks, (0, "fix outage"))  # smallest first: a min-heap
heapq.heappush(tasks, (5, "refactor"))
assert tasks[0] == (0, "fix outage")
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_heapq.py

Parameters

heap
A list already in heap order (an empty list is).
item
Comparable with the other items.

Behaviour

Returns
None.
Errors and preconditions
TypeError if items cannot be compared.
Changes
The list grows by 1.
Memory and invalidation
May reallocate the list.