CKTIS / Python
heapq.heappush
Inserts an item into a minimum heap while preserving its ordering invariant.
Version: Python 3.14; repository image, production runtime not attested
Syntax
heapq.heappush(heap, item, /)Inserts an item into a minimum heap while preserving its ordering invariant.
Start with an empty heap or a valid heap. Adding a smaller item makes it available at the root immediately.
Start with an empty list or a valid min-heap. Insertion appends the item and moves it toward the root according to less-than comparisons, returning None. Adding 2 after 5 and 8 puts 2 at index zero. For tied priorities a unique sequence number in (priority, number, task) avoids comparing unorderable tasks.
from heapq import heappop, heappush
h = []
for i, task in enumerate([{}, {}]):
assert heappush(h, (2, i, task)) is None
assert heappop(h)[1] == 0 and heappop(h)[1] == 1
Examples
import heapq
heap = []
for value in [5, 8, 2]:
heapq.heappush(heap, value)
print(heap[0], len(heap))
Result
2 3
Start with an empty list or a valid min-heap. Insertion appends the item and moves it toward the root according to less-than comparisons, returning None. Adding 2 after 5 and 8 puts 2 at index zero. For tied priorities a unique sequence number in (priority, number, task) avoids comparing unorderable tasks.