heapq · Python
heappush
Appends an item and sifts it up to restore the heap order.
heapq.heappush(heap, item, /)
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(log n) (the list append is amortized O(1)) |
| Worst case | O(log n) |
| Extra space | O(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")
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.