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-heapreplace-method/ below:

Python heapq.heapreplace() Method - GeeksforGeeks

Python heapq.heapreplace() Method

Last Updated : 23 Jul, 2025

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)      

Output
Removed 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() method

heapq.heapreplace(heap, item)

Parameters Return Value

The 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():

Practical Example: Fixed-Size Priority Queue

Suppose 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)  

Output
Removed: 50
Top 3 scores: [60, 65, 70]

Explanation:

When to Use heapq.heapreplace()?

Use heapreplace() when:

Key Differences from Other Heap Operations 1. 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():

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