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. However, in Python, heaps are usually implemented as min-heaps which means the smallest element is always at the root of the tree, making it easy to access.
heapq module allows us to treat a list as a heap, providing efficient methods for adding and removing elements.
To use a heap queue in Python, we first need to import the heapq module. A heap queue is created from a list by calling the heapq.heapify() function, which rearranges the elements of the list into a valid heap structure.
import heapq
# Creating a list
li = [10, 20, 15, 30, 40]
# Convert the list into a heap
heapq.heapify(li)
print("Heap queue:", li)
Output
Heap queue: [10, 20, 15, 30, 40]
Push (heappush): Adds an element to the heap while maintaining the heap property.
Pop (heappop): Removes and returns the smallest element in the heap, again maintaining the heap property.
Peek: View the smallest element without removing it.
Heapify: Convert a regular list into a valid heap in-place.
Appending and Popping Simultaneously (heappushpop) : This function allows us to push an element onto the heap and pop the smallest element in one combined operation.
Find the n largest or n smallest (nlargest() and nsmallest()):
**[heapq.nlargest(n, iterable)](<https://www.geeksforgeeks.org/python-heapq-nsmallest-method>)** returns the n largest elements from the iterable.
heapq.nsmallest(n, iterable) returns the n smallest elements from the iterable.
Replace Operation:
heapq.heapreplace() function is a combination of pop and push. It pops the smallest element from the heap and inserts a new element into the heap, maintaining the heap property. This operation is useful when we want to replace the smallest element with a new value in a heap.
Merge Operation:
heapq.merge() function is used to merge multiple sorted iterables into a single sorted heap. It returns an iterator over the sorted values, which we can then iterate through.
This operation is efficient because it avoids sorting the elements from scratch. Instead, it merges already-sorted iterables in a way that maintains the heap property.