heapq.heappush() function inserts an element into a heap while maintaining the heap property. It is commonly used to build and manage min-heaps, priority queues and other heap-based data structures.
Example: The following example inserts elements into a heap using heappush().
import heapq
h = []
heapq.heappush(h, 10)
heapq.heappush(h, 5)
heapq.heappush(h, 20)
print(h)
Output
[5, 10, 20]
Explanation: heapq.heappush() inserts each element into h and automatically rearranges the heap so that the smallest element remains at index 0.
Syntax
heapq.heappush(heap, item)
Parameters:
- heap: The heap list where the element will be inserted.
- item: The value to be added to the heap.
Examples
Example 1: This example shows how heappush() maintains the min-heap property while inserting multiple values. The smallest element is always placed at the root of the heap.
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappush(h, 8)
heapq.heappush(h, 3)
print(h)
Output
[1, 3, 8, 5]
Explanation: Each call to heapq.heappush() inserts a value into h and rearranges the heap so that the minimum element stays at index 0.
Example 2: Since heapq implements a min-heap, we can simulate a max-heap by inserting negative values.
import heapq
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, -x)
print([-x for x in h])
Output
[8, 3, 5, 1]
Explanation: Negative values are inserted using heapq.heappush(). The heap is maintained on negative numbers, and [-x for x in h] converts them back to positive values.
Example 3: This example uses tuples where the first value represents the priority and the second value represents the task.
import heapq
pq = []
heapq.heappush(pq, (2, "Task A"))
heapq.heappush(pq, (1, "Task B"))
heapq.heappush(pq, (3, "Task C"))
print(pq)
Output
[(1, 'Task B'), (2, 'Task A'), (3, 'Task C')]
Explanation: heapq.heappush() orders the tuples based on the first element (priority). The task with the lowest priority value appears at the root of the heap.