Python heapq.heappushpop() Method
Last Updated :
17 Mar, 2025
The heapq.heappushpop() method is part of Python's heapq module, which provides an efficient way to implement heaps (also known as priority queues). This method is a combination of two operations: heappush() and heappop(). It allows you to push a new element onto the heap and then pop the smallest element in one atomic operation, ensuring efficiency in heap-based algorithms.
Example:
Python
import heapq
# Create a heap
a = [1, 3, 5, 7, 9, 2]
# Convert the list into a heap
heapq.heapify(a)
# Push an element (4) and pop the smallest element
smallest = heapq.heappushpop(a, 4)
print("Removed element:", smallest)
print("Heap after pushpop:", a)
OutputRemoved element: 1
Heap after pushpop: [2, 3, 4, 7, 9, 5]
Explanation:
- The method first pushes 4 onto the heap, and then pops and returns the smallest element (1). After the operation, the heap is updated to [2, 3, 4, 7, 9, 5], with 1 removed.
Syntax of heappushpop() method
heapq.heappushpop(heap, item)
Parameters
- heap (list): A list that represents the heap. It should already be a valid heap structure.
- item (any type): The element that you want to push onto the heap.
Return Value
The method returns the smallest element from the heap before the new item is added. After the operation, the heap is modified in place, with the new element added and the heap property maintained.
Examples of heappushpop() method
1. Using heapq.heappushpop() with a Priority Queue
We can use heapq.heappushpop() in priority queue implementations where you want to efficiently push a new task with a priority and remove the task with the highest priority (the smallest element).
Python
import heapq
# List of tasks with (priority, task)
a = [(2, "Task A"), (1, "Task B"), (3, "Task C")]
# Convert the list into a heap
heapq.heapify(a)
# Add a new task (priority 0) and remove the highest priority task
removed_task = heapq.heappushpop(a, (0, "Task D"))
print("Removed task:", removed_task)
print("Priority Queue after pushpop:", a)
OutputRemoved task: (0, 'Task D')
Priority Queue after pushpop: [(1, 'Task B'), (2, 'Task A'), (3, 'Task C')]
Explanation: The smallest priority task (1, 'Task B') is removed, and the new task (0, 'Task D') with higher priority is added. The priority queue is updated accordingly.
2. Using heappushpop() with a Max-Heap Simulation
Since the heapq module only supports min-heaps, you can simulate a max-heap by negating the values. The heappushpop() method can then be used to manage the heap with negated values.
Python
import heapq
# Simulating a max-heap with negated values
h = [-1, -3, -5, -7, -9, -2]
# Convert the list into a heap
heapq.heapify(h)
# Push the element (-4) and pop the largest element (simulated)
largest = -heapq.heappushpop(h, -4)
print(largest)
print([-x for x in h])
Output9
[7, 4, 5, 1, 3, 2]
Explanation: The largest element 9 (in the original list) is removed, and the new element 4 is added. The result is a simulated max-heap [7, 4, 5, 3, 1, 2].
When to Use heapq.heappushpop()?
You should use heapq.heappushpop() when:
- Replacing the Root Element: When you want to replace the smallest element in the heap with a new one, and you want to do it efficiently in a single step.
- Priority Queues: In cases where you need to update a priority queue by adding a new task and removing the task with the smallest priority.
- Efficient Management of Heaps: When working with algorithms like Dijkstra's shortest path, where you need to pop and push elements to and from the heap frequently.
Similar Reads
Python heapq.heappop() Method The heapq.heappop() function in Python is used to pop and return the smallest element from a heap, maintaining the heap property. This function is extremely useful in situations where the smallest element in a min-heap needs to be processed first, such as in priority queues or sorting algorithms.Exa
4 min read
Python heapq.heapify() Method The heapq.heapify() function in Python is used to transform a regular list into a valid min-heap. A min-heap is a binary tree where the smallest element is always at the root. This method is highly useful when you need to create a heap structure from an unordered list and maintain the heap property
4 min read
Python heapq.heapreplace() Method The heapq.heapreplace() function removes and returns the smallest element from a heap (the root) and inserts a new item into the heap, all while maintaining the heap property. This is more efficient than performing separate heappop() and heappush() operations because it minimizes the number of heap
4 min read
Python heapq.merge() Method The heapq.merge() method in Python is part of the heapq module, which is used for heap-related operations. This method allows you to merge multiple sorted input iterables into a single sorted output iterable, efficiently using the heap data structure. It is particularly useful when working with sort
4 min read
Python heapq.nlargest() Method The heapq.nlargest() method in Python is a useful function from the heapq module that returns the n largest elements from an iterable, such as a list or tuple. This method is particularly handy when we want to quickly find the largest elements from a dataset, using a heap-based approach.Basic Exampl
4 min read
Heap queue or heapq in Python A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
7 min read
Python heapq.nsmallest() Method The heapq.nsmallest() method in Python is part of the heapq module and is used to retrieve the n smallest elements from an iterable, such as a list, tuple or other iterable objects. This method is highly useful when you need to efficiently find the smallest elements in a dataset, without sorting the
4 min read
Min Heap in Python A Min-Heap is a Data Structure with the following properties.It is a complete Complete Binary Tree.The value of the root node must be the smallest among all its descendant nodes and the same thing must be done for its left and right sub-tree also.Table of ContentExample of Min HeapMin Heap Represent
5 min read
Max Heap in Python A Max-Heap is a Data Structure with the following properties:It is a Complete Binary Tree.The value of the root node must be the largest among all its descendant nodes, and the same thing must be done for its left and right sub-tree also.How is Max Heap represented? A max Heap is a Complete Binary T
6 min read