Heap queue (or heapq) in Python - GeeksforGeeks

11 Sep, 2020
Heap data structure is mainly used to represent a priority queue. In Python, it is available using “heapq” module. The property of this data structure in Python is that each time the smallest of heap element is popped(min heap). Whenever elements are pushed or popped, heap structure in maintained. The heap[0] element also returns the smallest element each time.
Let’s see various Operations on heap :
heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order.
heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.
# Python code to demonstrate working of # heapify(), heappush() and heappop()  # importing "heapq" to implement heap queueimport heapq  # initializing listli = [5, 7, 9, 1, 3]  # using heapify to convert list into heapheapq.heapify(li)  # printing created heapprint ("The created heap is : ",end="")print (list(li))  # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4)  # printing modified heapprint ("The modified heap after push is : ",end="")print (list(li))  # using heappop() to pop smallest elementprint ("The popped and smallest element is : ",end="")print (heapq.heappop(li))
Output :
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1

heappushpop(heap, ele) :- This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation.
heapreplace(heap, ele) :- This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then the element is pushed.i.e, the value larger than the pushed value can be returned. heapreplace() returns the smallest value originally in heap regardless of the pushed element as opposed to heappushpop().
# Python code to demonstrate working of # heappushpop() and heapreplce()  # importing "heapq" to implement heap queueimport heapq  # initializing list 1li1 = [5, 7, 9, 4, 3]  # initializing list 2li2 = [5, 7, 9, 4, 3]  # using heapify() to convert list into heapheapq.heapify(li1)heapq.heapify(li2)  # using heappushpop() to push and pop items simultaneously# pops 2print ("The popped item using heappushpop() is : ",end="")print (heapq.heappushpop(li1, 2))  # using heapreplace() to push and pop items simultaneously# pops 3print ("The popped item using heapreplace() is : ",end="")print (heapq.heapreplace(li2, 2))
Output :
The popped item using heappushpop() is : 2
The popped item using heapreplace() is : 3

nlargest(k, iterable, key = fun) :- This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned.
nsmallest(k, iterable, key = fun) :- This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned.
# Python code to demonstrate working of # nlargest() and nsmallest()  # importing "heapq" to implement heap queueimport heapq  # initializing list li1 = [6, 7, 9, 4, 3, 5, 8, 10, 1]  # using heapify() to convert list into heapheapq.heapify(li1)  # using nlargest to print 3 largest numbers# prints 10, 9 and 8print("The 3 largest numbers in list are : ",end="")print(heapq.nlargest(3, li1))  # using nsmallest to print 3 smallest numbers# prints 1, 3 and 4print("The 3 smallest numbers in list are : ",end="")print(heapq.nsmallest(3, li1))
Output :
The 3 largest numbers in list are : [10, 9, 8]
The 3 smallest numbers in list are : [1, 3, 4]

YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Heap in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=nXp7lg2SVQo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shreyashagrawal
priority-queue
Python
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()