A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-heapq-heappush-method/ below:

Python heapq.heappush() Method - GeeksforGeeks

Python heapq.heappush() Method

Last Updated : 11 Mar, 2025

The heapq.heappush() function in Python is used to push an element onto a heap while maintaining the heap property. This function is useful when dealing with priority queues or implementing efficient sorting algorithms.

Example:

Python
import heapq

# Create an empty list that will represent the heap
h = []

# Use heappush to add elements to the heap
heapq.heappush(h, 10)
heapq.heappush(h, 5)
heapq.heappush(h, 20)
heapq.heappush(h, 15)

# Print the heap after adding elements
print(h)

Explanation:

Syntax of heappush() method

heapq.heappush(heap, item)

Parameters Return Value

This function does not return anything. It modifies the heap in-place by inserting the new element while maintaining the heap property.

Examples of heappush() method 1. Using heappush() to Insert Elements in a Min-Heap Python
import heapq

# Create an empty heap
h = []

# Push elements onto the heap
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappush(h, 8)
heapq.heappush(h, 3)

print("Min-Heap:", h)

Output
Min-Heap: [1, 3, 8, 5]

Explanation:

2. Using heappush() in a Max-Heap

Since heapq only supports min-heaps, we can simulate a max-heap by pushing negative values.

Python
import heapq

h = []

# Push elements as negative values to simulate max-heap
heapq.heappush(h, -5)
heapq.heappush(h, -1)
heapq.heappush(h, -8)
heapq.heappush(h, -3)

# Convert back to positive for correct order
max_heap = [-x for x in h]

print("Max-Heap:", max_heap)

Output
Max-Heap: [8, 3, 5, 1]

Explanation:

3. Using heappush() in a Priority Queue

heapq.heappush() is commonly used in priority queues, where elements are inserted based on their priority.

Python
import heapq

# List of tuples (priority, task)
pq= []

# Push elements (priority, task)
heapq.heappush(pq, (2, "Task A"))
heapq.heappush(pq, (1, "Task B"))
heapq.heappush(pq, (3, "Task C"))

print("Priority Queue:", pq)

Output
Priority Queue: [(1, 'Task B'), (2, 'Task A'), (3, 'Task C')]

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4