This post will discuss how to implement max heap in Python based on the heapq module.

1. Max Heap of primitives

The heapq module in Python provides the min-heap implementation of the priority queue algorithm. We can easily implement max heap data structure using it.

The following program provides a simple implementation of max heap for integers using heapq operations. It can be easily extended to support any other general-purpose functions based on heaps.

Download  Run Code

Output:

9
7
6
10
9

2. Max Heap of Objects

For objects, we can directly use the heapq module in Python to get a max heap. The idea is to override the less-than operator __lt__ to make our class work with max heap. The following program demonstrates this:

Download  Run Code

Output:

(9, 4)
(7, 0)
(6, 2)
(4, 1)
(3, 3)
(1, 5)

That’s all about max heap implementation in Python using the heapq module.