Python provides so many inbuilt data structures like List, Dictionary, Tuple, str , set etc . Heap is also one of the most useful data structure in python . This article will help you in finding out How to create Heaps in Python?
Do you know python has its very specific module heapq for dealing with the heap data structure. The heap module has several operations for creation, insertion, and replacement. Let’s understand one by one –
Creating a Heap in Python ( heapify )-
This function will convert the list to heap with the smallest element at the top. Here is the code –
import heapq List_element = [23,14,56,78,3,51] heapq.heapify(List_element ) print(List_element )
image -create Heaps in Python
Insert into Heap Python –
We can use heap push function for inserting element into existing heap but it will come at the last index . If you want to rearrange it only you may heapify again . then if the element which was recently pushed is the smallest after heapify it will come on top . Here is the complete code.
How to remove element in Heap Python ?
As we have heappush() function for insertion . In the same way we have heappop() function for removing the smallest element . Here is the example code for the reference –
As the above example is quite set explanatory but I will add few more line like heappop() function remove the smallest value which comes at the first index in heap .
There are so many application of heap in programming . Python is not an exception in this . Well heap implementation is quite easy in python just because of heapq module . This module provide perfect interface for creation , insertion and deletion in python by the name of heapify() , heappush(), heappop() .
I hope you guys have enough information about Heaps in Python . Please provide your feed back over this article .We are waiting for sugestions.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.