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.

Creating a Heap Queue

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]

Key operations of a heap: