The heapreplace function of the heapq module in Python pops the root node(i.e, the smallest element of the heap) and adds a new item while maintaining the heap property.
The min heap created by the heapq.heapify() maintains the lowest element of the heap at the root.
The heaprepalce() function of the Python heapq module pops the element at the root node and inserts an element into the min heap while maintaining the heap invariants.
Example
python
# Example Python program that pops an item and pushes another item
# using heapq.heapreplace() function
import heapq
# Construct a heap
elems = [1, 7, 3, 5, 2, 11, 19, 17, 13]
heapq.heapify(elems)
print("The initial heap is:")
print(elems)
print("Largest %d elements:"%len(elems))
sorted = heapq.nsmallest(len(elems), elems)
print(sorted)
# pop and replace once
heapq.heapreplace(elems, 23)
print("After calling heapreplace once")
print(elems)
# pop and replace again
heapq.heapreplace(elems, 29)
print("After calling heapreplace again")
print(elems)
Output
Output
The initial heap is:
[1, 2, 3, 5, 7, 11, 19, 17, 13]
Largest 9 elements:
[1, 2, 3, 5, 7, 11, 13, 17, 19]
After calling heapreplace once
[2, 5, 3, 13, 7, 11, 19, 17, 23]
After calling heapreplace again
[3, 5, 11, 13, 7, 29, 19, 17, 23]
Your privacy choices
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on