Syntax of Using heapq and PriorityQueue
Example 1: Using heapq
Here, we have used heapify() method to convert a list of items into heap. And then we used heapop() method to pop items one by one from the heapified list.
Python3
import heapq jobs = [( 1 , 'eat' ), ( 3 , 'code' ), ( 2 , 'sleep' )] heapq.heapify(jobs) for _ in range ( len (jobs)): popped_item = heapq.heappop(jobs) print (popped_item) |
Output:
(1, 'eat') (2, 'sleep') (3, 'code')
Example 2: Using PriorityQueue
Here, we have used .put() method to push an element to the PriorityQueue and get_nowait() to pop an element from the PriorityQueue. And the loop to pop the items from the PriorityQueue breaks when the PriorityQueue raises an Empty exception, which signifies, there are no more elements to be popped.
Python3
from queue import PriorityQueue, Empty prior_queue = PriorityQueue() jobs = [( 1 , 'eat' ), ( 3 , 'code' ), ( 2 , 'sleep' )] for job in jobs: prior_queue.put(job) while 1 : try : popped_item = prior_queue.get_nowait() print (popped_item) except Empty: break |
Output:
(1, 'eat') (3, 'code') (2, 'sleep')
Difference Between heapq and PriorityQueue in Python
In this article, we are going to see the difference between heapq and PriorityQueue in Python.
Contact Us