{"id":4030,"date":"2020-09-03T17:34:36","date_gmt":"2020-09-03T12:04:36","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=4030"},"modified":"2021-06-14T15:11:31","modified_gmt":"2021-06-14T09:41:31","slug":"python-priority-queue","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-priority-queue\/","title":{"rendered":"Understanding Priority Queue in Python with Implementation"},"content":{"rendered":"\n<p>Are you tired of hearing some strange concepts of data structures like <strong>priority queue<\/strong>? No more confusions because here you&#8217;ll get to know everything about the priority queue. And we will be using Python language to write some code so let&#8217;s say more specifically <strong>Python priority queue<\/strong>. We will use Python 3. Many people who have just begun to explore these Data structure terms like a queue, stack, heap and priority queue are usually confused between heap and priority queue. So we will talk about their differences and similarities.<\/p>\n\n\n\n<p id=\"definition\"><em>The priority queue in Python or any other language is a particular type of queue in which each element is associated with a priority and is served according to its preference. If elements with the same priority occur, they are performed according to their order in the queue. Generally, the value of the element itself is considered for assigning the priority.<\/em><\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_74 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #990303;color:#990303\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #990303;color:#990303\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#What_is_a_Priority_Queue_In-depth\" >What is a Priority Queue In-depth<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#How_Can_We_Implement_Priority_Queue_in_Python\" >How Can We Implement Priority Queue in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Implementing_Priority_Queue_Using_Sorted_List\" >Implementing Priority Queue Using Sorted List<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Implementing_Priority_Queue_Using_the_heapq_Module\" >Implementing Priority Queue Using the heapq Module<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Firstly_lets_implement_the_priority_queue_using_the_heapq_module_provided_by_Python_itself\" >Firstly let&#8217;s implement the priority queue using the heapq module provided by Python itself<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Demonstration_of_Max_heap\" >Demonstration of Max heap<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Time_Complexity_of_heapq\" >Time Complexity of heapq<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Implementing_Priority_Queue_Through_queuePriorityQueue_Class\" >Implementing Priority Queue Through queue.PriorityQueue&nbsp;Class<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Time_Complexity_Using_queuePriorityQueue_Class\" >Time Complexity Using queue.PriorityQueue Class<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Another_Not_Very_Popular_Method_of_Priority_Queue\" >Another Not Very Popular Method of Priority Queue<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Peek_implementation_of_Priority_Queue\" >Peek implementation of Priority Queue:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Applications_of_Priority_Queue\" >Applications of Priority Queue<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Must_Read\" >Must Read:<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_a_Priority_Queue_In-depth\"><\/span>What is a Priority Queue In-depth<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Simply, a priority queue is an ADT similar to queue in Data structure (a very important subject of CS major). But what makes it different from queue is the elements in Priority queue has some kind of priority over other elements.<\/p>\n\n\n\n<p><strong>What does priority of those elements mean to us? Do they really worth my time? <\/strong><em>Yes. <\/em>It is important for you to know why they exist if you are willing to learn and master Priority queue and other aspects of it like Python priority queue comparator or priority queue max size in python, etc.  They simply exist because <strong>priority decide the order of removal of those elements in Priority queue. <\/strong><\/p>\n\n\n\n<p>The queue (data structure) uses <strong>FIFO<\/strong> but the priority queue doesn&#8217;t remove it&#8217;s elements on basis of their arrivals. <\/p>\n\n\n\n<p>So, now as you&#8217;ve learnt the basic definition and terms of Priority queue. Let&#8217;s jump deeper and explore some of the operation on Python priority queue. <strong>What are some of the main or popular operations performed on priority queue? We can iterate through our priority queue or perform sorting on it. And also one can also change priority of elements in Pytho<\/strong>n priority queue or we will see some operations like Python priority queue decreasing key or updating values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_Can_We_Implement_Priority_Queue_in_Python\"><\/span>How Can We Implement Priority Queue in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There can be many ways to implement the priority queue in Python. But in this tutorial, we will talk about the <strong>best three ways to implement a priority queue in Python.<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Python sorted list<\/li><li>Using the heapq Module<\/li><li>Using&nbsp;<code>queue.PriorityQueue<\/code><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_Priority_Queue_Using_Sorted_List\"><\/span>Implementing Priority Queue Using Sorted List<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s start with an effortless and straightforward way. In this way, we will use a standard list, but we need to sort that list every time an item is added.<\/p>\n\n\n\n<p>Let\u2019s walk through an example of a priority queue using lists.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1:<\/h4>\n\n\n\n<p>Suppose we want to create a priority queue that stores the order of students who should be let into a seminar first. Then we can use the following code to create a priority queue using lists:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nstudent_pass = &#x5B;]\n\nstudent_pass.append((3, 'Ram'))\nstudent_pass.append((1, 'Sham'))\nstudent_pass.append((2, 'Vasu'))\n\n# NOTE: Remember to re-sort every time\n#       a new element is inserted, or use\n#       bisect.insort().\n\nstudent_pass.sort(reverse=True)\n\nwhile student_pass:\n\titem = student_pass.pop()\n\tprint(item)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(1, 'Sham')\n(2, 'Vasu')\n(3, 'Ram')<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Time Complexity of Priority Queue Using Sorted List<\/h4>\n\n\n\n<p>Maintaining the order by appending to the list and re-sorting also takes at least&nbsp;<em><strong>O(n log n)<\/strong><\/em>&nbsp;time. Thus, it is only efficient when we have to make a few insertions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_Priority_Queue_Using_the_heapq_Module\"><\/span>Implementing Priority Queue Using the heapq Module<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before implementing and jumping directly to the examples. We must know all the building blocks of the structure i.e, Heap, queue, priority queue etc.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">What exactly are a heap and priority queue in Python? <\/h4>\n\n\n\n<p>So, priority queue is implemented in Python (not only in Python) using Binary Heap or you&#8217;d say it heap queue (heapq below in this article).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">What is heap(heapq) ? <\/h4>\n\n\n\n<p>A Heap is a tree based Data structure also known as heap priority. (In Simple words, you can say priority queue in Python uses heap to classify the elements)<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">What is a queue ?<\/h4>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" src=\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/2942529-1024x1024.jpg\" alt=\"Python Priority Queue\" class=\"wp-image-4039\" width=\"346\" height=\"344\"\/><figcaption><strong>A queue<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p><em>A queue of humans, imagine someone holding a premium pass, so he\/she will be given more priority over others similarly in Priority Queue.<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Firstly_lets_implement_the_priority_queue_using_the_heapq_module_provided_by_Python_itself\"><\/span>Firstly let&#8217;s implement the priority queue using the heapq module provided by Python itself<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\"><div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nq = &#x5B;]\n\nheapq.heappush(q, (3, 'A')) #heappush is a method to add an \nheapq.heappush(q, (1, 'B')) #element\nheapq.heappush(q, (2, 'C'))\n\nwhile q:\n    next_item = heapq.heappop(q) #heappop is a method to\n    print(next_item) #remove an element\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(1, 'B')\n(2, 'C')\n(3, 'A')<\/code><\/pre>\n<\/div><\/div>\n\n\n\n<p>You may have came across many questions like min heap and max heap. Or may be you&#8217;d have read something like priority queue max size python etc. So here&#8217;s the answer to all of these scary questions. Here we are using heapq module\/class in Python. Remember, which is default use for <a href=\"http:\/\/www.pythonpool.com\/numpy-argmin\/\" target=\"_blank\" rel=\"noopener\">min<\/a> heap. To use it for max heap multiply each element by negative 1 i.e -1<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Demonstration_of_Max_heap\"><\/span>Demonstration of Max heap<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#demonstartion of max heap using heapq in python 3\n  \nfrom heapq import heappop, heappush, heapify \n# An empty heap has been created\nheap = &#x5B;] \nheapify(heap) \n\n\nheappush(heap, -1 * 10) #adding elements using heappush\nheappush(heap, -1 * 30) # function by multiplying them with\nheappush(heap, -1 * 20) #-1\nheappush(heap, -1 * 400) \n\n# printing the value of maximum element \nprint(&quot;Head value of heap : &quot;+str(-1 * heap&#x5B;0])) \n\n  \n# print all elements in the heap\nprint(&quot;The elements in heap: &quot;) \n\nfor i in heap: \n    print(-1 * i, end = ' ') \nprint(&quot;\\n&quot;) \nelement = heappop(heap) \n\n  \n# printing the elements of the heap \n\nprint(&quot;The heap elements: &quot;) \n\nfor i in heap: \n    print(-1 * i, end = ' ') \n\n\n#Result of above code after execution\n#Head value of heap: 400\n#The heap elements : \n#400 30 20 10 \n\n#The heap elements : \n#30 10 20 \n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Time_Complexity_of_heapq\"><\/span>Time Complexity of heapq<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <strong>heapq<\/strong> implementation has&nbsp;<code>O(log n)<\/code>&nbsp;time for insertion and extraction of the smallest element. Note that&nbsp;<code>heapq<\/code>&nbsp;only has a&nbsp;<code>min<\/code>&nbsp;heap implementation, but there are ways to use as a&nbsp;<code>max<\/code>&nbsp;heap.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_Priority_Queue_Through_queuePriorityQueue_Class\"><\/span>Implementing Priority Queue Through queue.PriorityQueue&nbsp;Class<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Another way to create a priority queue in Python 3 is by <strong>PriorityQueue class<\/strong> provide by Python 3<strong>. <\/strong>(<em>you can also use it in Python 2 but sadly Python 2 is no more in the use)<\/em>. And also below code could help you to <a href=\"http:\/\/www.pythonpool.com\/python-iterate-through-list\/\" target=\"_blank\" rel=\"noreferrer noopener\">iterate<\/a> over priority queue in Python or (some people may call it just ) <strong>priority queue in Data structure.<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom queue import PriorityQueue\n\nq = PriorityQueue()\n\nq.put((2, 'code'))\nq.put((1, 'eat'))\nq.put((3, 'sleep'))\n\nwhile not q.empty():\n    next_item = q.get()\n    print(next_item)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(1, 'eat')\n(2, 'code')\n(3, 'sleep')<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Time_Complexity_Using_queuePriorityQueue_Class\"><\/span>Time Complexity Using queue.PriorityQueue Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The&nbsp;<code>queue.PriorityQueue<\/code>&nbsp;uses the same&nbsp;<code>heapq<\/code>&nbsp;implementation from internally and thus has the same time complexity which is &nbsp;<code>O(log n)<\/code> . However, it is different in two key ways. Firstly, it is&nbsp;<em>synchronized,&nbsp;<\/em>so it supports concurrent processes. Secondly, it is a&nbsp;<code>class<\/code>&nbsp;interface instead of the&nbsp;<code>function<\/code>&nbsp;based interface of&nbsp;<code>heapq<\/code>&nbsp;. Thus,&nbsp;<code>queue.PriorityQueue<\/code>&nbsp;is the classic OOP style of implementing and using Priority Queues.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Another_Not_Very_Popular_Method_of_Priority_Queue\"><\/span>Another Not Very Popular Method of Priority Queue<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There is many methods or ways to implement priority queues in python. One of the not very popular method is by <a href=\"https:\/\/docs.python.org\/3\/tutorial\/datastructures.html\" target=\"_blank\" rel=\"noreferrer noopener\">peek<\/a> implementation which is shown below.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Peek_implementation_of_Priority_Queue\"><\/span>Peek implementation of Priority Queue:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong>What is peek in Priority queue? <\/strong>So<strong> <\/strong>if you use java then peek() is just another method on priority queue which gives you the 1st element of priority queue. But in python 3 as we are learning about priority queue in Python 3, we don&#8217;t have any built-in method like peek(). So we have to write it&#8217;s implementation.<\/p>\n\n\n\n<p>Here&#8217;s is the code for peek in Python priority queue (the below code is executable on Python 3.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport queue\n\nclass PeekablePriorityQueue(queue.PriorityQueue):\n    def peek(self):\n        &quot;&quot;&quot;Peeks the first element of the queue\n        \n        Returns\n        -------\n        item : object\n            First item in the queue\n        \n        Raises\n        ------\n        queue.Empty\n            No items in the queue\n        &quot;&quot;&quot;\n        try:\n            with self.mutex:\n                return self.queue&#x5B;0]\n        except IndexError:\n            raise queue.Empty\n<\/pre><\/div>\n\n\n<p>There&#8217;s so many more methods or modules or class available in python 3 library you can refer. And so many operations you can perform on priority queue like itrating through it, decrease key, update values, etc <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Applications_of_Priority_Queue\"><\/span>Applications of Priority Queue<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s explore the applications of Priority queue:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Priority queues are used in <strong>operating system<\/strong> for giving priority to a important task over other or simply interruption handling.<\/li><li>In <strong>traffic light, depending upon the traffic, the colors will be given priority.<\/strong><\/li><li>Implementing <strong>Dijkstra&#8217;s algorithm<\/strong> through Priority Queue.<\/li><li>We can <strong>sort heaps<\/strong> through priority queues.<\/li><li> <strong>Prim&#8217;s algorithm<\/strong> implementation can be done using priority queues.<\/li><\/ol>\n\n\n\n<h2 class=\"has-vivid-red-color has-text-color wp-block-heading\"><span class=\"ez-toc-section\" id=\"Must_Read\"><\/span>Must Read:<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"http:\/\/www.pythonpool.com\/python-lowercase\/\">How to Convert String to Lowercase in<\/a><\/li><li><a href=\"http:\/\/www.pythonpool.com\/square-root-in-python\/\">How to Calculate Square Root<\/a><\/li><li><a href=\"http:\/\/www.pythonpool.com\/python-user-input\/\">User Input | Input () Function | Keyboard Input<\/a><\/li><li><a href=\"http:\/\/www.pythonpool.com\/python-book\/\">Best Book to Learn Python in 2020<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In <strong>Python<\/strong>, there are many different ways to implement a <strong>priority queue<\/strong>. The two most common options to create a priority queue are to use the <strong>heapq <\/strong>module, or to use the&nbsp;<code>queue.PriorityQueue<\/code>&nbsp;class.<\/p>\n\n\n\n<p>If you have made it to the end, you&#8217;re now an <em>expert on the topic of priority queue in Data structure with Python.<\/em> You can perform all kind of operations on it and use its many of the above mentioned applications in solving problems. Remember to implement your learnings in Python 3 and not other versions like Python 2.<\/p>\n\n\n\n<p>Try to implement the programs on your side and let us know if you have any queries in the comment section below.<\/p>\n\n\n\n<p><strong><em>Happy Pythoning!<\/em><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Are you tired of hearing some strange concepts of data structures like priority queue? No more confusions because here you&#8217;ll get to know everything about &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Understanding Priority Queue in Python with Implementation\" class=\"read-more button\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/#more-4030\" aria-label=\"More on Understanding Priority Queue in Python with Implementation\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":4084,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[15],"tags":[2157,2160,2167,2168,2162,2166,2158,2169,2171,2153,2163,2155,2147,2149,2170,2150,2164,2146,2151,2159,1595,2156,2152,2148,2154,2161,2165],"class_list":["post-4030","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-implement-max-heap-using-heapq","tag-priority-queue-fifo-python","tag-priority-queue-in-data-structure","tag-priority-queue-in-python","tag-priority-queue-max-size-python","tag-priority-queue-python","tag-priority-queue-python-3","tag-priority-queue-python-example","tag-priority-queue-python-tuples","tag-priority-queue-two-parameters-python","tag-python-3-priority-queue","tag-python-add-to-priority-queue","tag-python-check-if-item-in-priority-queue","tag-python-heapq-custom-comparator","tag-python-priority-queue","tag-python-priority-queue-change-priority","tag-python-priority-queue-comparator","tag-python-priority-queue-comparator-iterate-over-priority-queue-python","tag-python-priority-queue-decrease-key","tag-python-priority-queue-example","tag-python-priority-queue-max-heap","tag-python-priority-queue-peek","tag-python-priority-queue-reverse-order","tag-python-priority-queue-sorting","tag-python-priority-queue-update-value","tag-python-priorityqueue-key","tag-queue-priorityqueue","infinite-scroll-item"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.1 (Yoast SEO v25.0) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Understanding Priority Queue in Python with Implementation - Python Pool<\/title>\n<meta name=\"description\" content=\"Priority queue in Python or in general is a type of queue in which each element is associated with a priority and is served accordingly.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonpool.com\/python-priority-queue\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Understanding Priority Queue in Python with Implementation\" \/>\n<meta property=\"og:description\" content=\"Are you tired of hearing some strange concepts of data structures like priority queue? No more confusions because here you&#039;ll get to know everything about\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-priority-queue\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2020-09-03T12:04:36+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-06-14T09:41:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1350\" \/>\n\t<meta property=\"og:image:height\" content=\"650\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Python Pool\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:site\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Python Pool\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/\"},\"author\":{\"name\":\"Python Pool\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/f87448ee54c0ffd2889fbf2408c18998\"},\"headline\":\"Understanding Priority Queue in Python with Implementation\",\"datePublished\":\"2020-09-03T12:04:36+00:00\",\"dateModified\":\"2021-06-14T09:41:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/\"},\"wordCount\":1306,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png\",\"keywords\":[\"implement max-heap using heapq\",\"priority queue fifo python\",\"priority queue in data structure\",\"priority queue in python\",\"priority queue max size python\",\"priority queue python\",\"priority queue python 3\",\"priority queue python example\",\"priority queue python tuples\",\"priority queue two parameters python\",\"python 3 priority queue\",\"python add to priority queue\",\"python check if item in priority queue\",\"python heapq custom comparator\",\"python priority queue\",\"python priority queue change priority\",\"python priority queue comparator\",\"python priority queue comparator iterate over priority queue python\",\"python priority queue decrease-key\",\"python priority queue example\",\"python priority queue max heap\",\"python priority queue peek\",\"python priority queue reverse order\",\"python priority queue sorting\",\"python priority queue update value\",\"python priorityqueue key\",\"queue priorityqueue\"],\"articleSection\":[\"Tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.pythonpool.com\/python-priority-queue\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/\",\"url\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/\",\"name\":\"Understanding Priority Queue in Python with Implementation - Python Pool\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png\",\"datePublished\":\"2020-09-03T12:04:36+00:00\",\"dateModified\":\"2021-06-14T09:41:31+00:00\",\"description\":\"Priority queue in Python or in general is a type of queue in which each element is associated with a priority and is served accordingly.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pythonpool.com\/python-priority-queue\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage\",\"url\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png\",\"contentUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png\",\"width\":1350,\"height\":650,\"caption\":\"Python Priority Queue\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pythonpool.com\/python-priority-queue\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pythonpool.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Understanding Priority Queue in Python with Implementation\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.pythonpool.com\/#website\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"name\":\"Python Pool\",\"description\":\"Your One-Stop Python Learning Destination\",\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.pythonpool.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.pythonpool.com\/#organization\",\"name\":\"Python Pool\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\",\"url\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"contentUrl\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"width\":452,\"height\":185,\"caption\":\"Python Pool\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/pythonpool\",\"https:\/\/www.youtube.com\/c\/pythonpool\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/f87448ee54c0ffd2889fbf2408c18998\",\"name\":\"Python Pool\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g\",\"caption\":\"Python Pool\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Understanding Priority Queue in Python with Implementation - Python Pool","description":"Priority queue in Python or in general is a type of queue in which each element is associated with a priority and is served accordingly.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonpool.com\/python-priority-queue\/","og_locale":"en_US","og_type":"article","og_title":"Understanding Priority Queue in Python with Implementation","og_description":"Are you tired of hearing some strange concepts of data structures like priority queue? No more confusions because here you'll get to know everything about","og_url":"https:\/\/www.pythonpool.com\/python-priority-queue\/","og_site_name":"Python Pool","article_published_time":"2020-09-03T12:04:36+00:00","article_modified_time":"2021-06-14T09:41:31+00:00","og_image":[{"width":1350,"height":650,"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png","type":"image\/png"}],"author":"Python Pool","twitter_card":"summary_large_image","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Python Pool","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/"},"author":{"name":"Python Pool","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/f87448ee54c0ffd2889fbf2408c18998"},"headline":"Understanding Priority Queue in Python with Implementation","datePublished":"2020-09-03T12:04:36+00:00","dateModified":"2021-06-14T09:41:31+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/"},"wordCount":1306,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png","keywords":["implement max-heap using heapq","priority queue fifo python","priority queue in data structure","priority queue in python","priority queue max size python","priority queue python","priority queue python 3","priority queue python example","priority queue python tuples","priority queue two parameters python","python 3 priority queue","python add to priority queue","python check if item in priority queue","python heapq custom comparator","python priority queue","python priority queue change priority","python priority queue comparator","python priority queue comparator iterate over priority queue python","python priority queue decrease-key","python priority queue example","python priority queue max heap","python priority queue peek","python priority queue reverse order","python priority queue sorting","python priority queue update value","python priorityqueue key","queue priorityqueue"],"articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-priority-queue\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/","url":"https:\/\/www.pythonpool.com\/python-priority-queue\/","name":"Understanding Priority Queue in Python with Implementation - Python Pool","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png","datePublished":"2020-09-03T12:04:36+00:00","dateModified":"2021-06-14T09:41:31+00:00","description":"Priority queue in Python or in general is a type of queue in which each element is associated with a priority and is served accordingly.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-priority-queue\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/09\/Theatre-Actor-Portfolio-Website.png","width":1350,"height":650,"caption":"Python Priority Queue"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-priority-queue\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Understanding Priority Queue in Python with Implementation"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonpool.com\/#website","url":"https:\/\/www.pythonpool.com\/","name":"Python Pool","description":"Your One-Stop Python Learning Destination","publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonpool.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonpool.com\/#organization","name":"Python Pool","url":"https:\/\/www.pythonpool.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/","url":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","contentUrl":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","width":452,"height":185,"caption":"Python Pool"},"image":{"@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/pythonpool","https:\/\/www.youtube.com\/c\/pythonpool"]},{"@type":"Person","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/f87448ee54c0ffd2889fbf2408c18998","name":"Python Pool","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g","caption":"Python Pool"}}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/4030","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=4030"}],"version-history":[{"count":32,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/4030\/revisions"}],"predecessor-version":[{"id":24518,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/4030\/revisions\/24518"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/4084"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=4030"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=4030"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=4030"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}