Python heapq example : Different Scenarios with Implementation

Python heapq example Different Scenarios with Implementation

Python heapq example makes easy to understand heap data structure in Python.Python heapq has three main function ( heapify(),heappop(),heappush() ).

Various python heapq examples –

Lets see some examples. It will easily make you understand the concepts of heap in python.

1. python heapq example (heapify()):

If we have any iterable object like list, tuple, We can convert it to heap.Using the above heapify function.Lets see an example for heap creation in python.

import heapq 
#any list, tuple or any tother iterable obj
iterable_obj = [15, 71, 9, 11, 13] 
# heap conversions
print (iterable_obj) 
python heapq example
python heapq example


Here we have  used a list object as iterable. After applying heapify operation over this list the minimum value come at the top. In our example the min value was “9”. Hence it is coming at first indices in heap (min).

2.  heappush() example:

When we need to insert a new element in already created heap object. We use this heappush() function heapq python module.Lets checkout and example.

If we create a new node or insert a new value in heap. It will reconstruct and whole heap object. Hence again the smallest element will be on the root place.

python heapq heappush
python heapq heappush

In the above example, We have inserted an new element “2” in the heap. It has reshuffle the position of reach element in the heap. But the smallest element is on the root.


 3. heappop() example :

This function will always pop the smallest value from the heap.Lets apply the heappop() function in the heap which we have created in the above sections.

print("Heap before appling tge heappop()")
#appling heappop()
print("Heap after appling tge heappop()")
python heapq heappop()
python heapq heappop()


4. Others heapq functions:

4.1  heapreplace() :

It will fist heappop() the object. After this it will push the new element. Hence It is a chain of the heappop() and heappush() operation.

4.2 heappushpop():

This a little different then the above heapreplace()  function. It will first push the element in the heap. Then it will heappop() the complete object.



Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages, where he and his team share knowledge and help others learn more about data science.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner