Python heapq.heapreplace() Method Last Updated : 21 Apr, 2025 Comments Improve Suggest changes Like Article Like Report 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 adjustments.Example: Python import heapq # Create a list and convert it to a heap a = [3, 5, 7, 10] heapq.heapify(a) # Replace the smallest element with 4 smallest = heapq.heapreplace(a, 4) print("Removed item:", smallest) print("Updated heap:", a) OutputRemoved item: 3 Updated heap: [4, 5, 7, 10] Explanation: The smallest item (3) is removed and returned and the new item (4) is inserted, and the heap adjusts itself.Syntax of heapreplace() methodheapq.heapreplace(heap, item)Parametersheap: A list that has been transformed into a heap using heapq.heapify() or built incrementally with heapq.heappush().item: The new item to be inserted into the heap.Return ValueThe method returns the smallest element that was removed from the heap.How Does heapq.heapreplace() Work?A heap in Python is a binary tree represented as a list where the smallest element is always at index 0 (min-heap property). When you call heapreplace():The smallest element (at the root) is removed and returned.The new item is inserted into the heap.The heap is restructured to maintain the heap property, ensuring the smallest element is again at the root.Practical Example: Fixed-Size Priority QueueSuppose you’re tracking the 3 highest scores in a game, but you only want to store the top 3 at any time: Python import heapq # Initialize a heap with the first 3 scores s = [50, 60, 70] heapq.heapify(s) # New score comes in ns = 65 smallest = heapq.heapreplace(s, ns) print("Removed:", smallest) print("Top 3 scores:", s) OutputRemoved: 50 Top 3 scores: [60, 65, 70] Explanation:The code initializes a heap with scores [50, 60, 70] and uses heapq.heapify() to convert it into a heap.A new score 65 is added using heapq.heapreplace(), which replaces the smallest element (50).The removed smallest element is printed, and the updated heap is shown: [60, 65, 70].When to Use heapq.heapreplace()?Use heapreplace() when:You need to update a heap by replacing the smallest element with a new value.Efficiency is critical, and you want to avoid separate pop and push operations.You’re maintaining a fixed-size heap (e.g., tracking the top k elements) and need to replace the smallest item with a new candidate.Key Differences from Other Heap Operations1. Compared to heappop() followed by heappush():heapreplace() is more efficient because it performs the replacement in one step, avoiding unnecessary heap adjustments.Example of separate operations:smallest = heapq.heappop(heap) # O(log n)heapq.heappush(heap, 4) # O(log n)This takes two O(log n) steps, while heapreplace() does it in one.2. Compared to heappushpop():heappushpop(heap, item) pushes the new item first and then pops the smallest item. If the new item is smaller, it gets popped immediately.heapreplace() always removes the smallest item and adds the new one, regardless of the new item’s value. Comment More infoAdvertise with us Next Article Python heapq.heapreplace() Method B brijkan3mz4 Follow Improve Article Tags : Python Python-DSA Data Structures-Heap Practice Tags : python Similar Reads 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.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.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.heappushpop() Method 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 e 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 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 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 List methods Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, weâll explore all Python list methods with a simple example.List MethodsLet's look at different list methods in Python:append(): Adds an 3 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 Like