Your confusion may come from the fact that the Python module heapq
does not define a heap as a data type (a class) with its own methods (e.g. as in a deque
or a list
). It instead provides functions that you can run on a Python list
.
It's best to think of heapq
as a module providing a set of algorithms (methods) to interpret lists as heaps and manipulate them accordingly. Note that it's common to represent heaps internally as arrays (as an abstract data structure), and Python already has lists serving that purpose, so it makes sense for heapq
to just provide methods to manipulate lists as heaps.
Let's see this with an example. Starting with a simple Python list:
>>> my_list = [2, -1, 4, 10, 0, -20]
To create a heap with heapq
from my_list
we just need to call heapify
which simply re-arranges the elements of the list to form a min-heap:
>>> import heapq
>>> # NOTE: This returns NoneType:
>>> heapq.heapify(my_list)
Note that you can still access the list underlying the heap, since all heapify
has done is change the value referenced by my_list
:
>>> my_list
[-20, -1, 2, 10, 0, 4]
Popping elements from the heap held by my_list
:
>>> [heapq.heappop(my_list) for x in range(len(my_list))]
[-20, -1, 0, 2, 4, 10]