{"id":26449,"date":"2023-05-30T13:22:31","date_gmt":"2023-05-30T07:52:31","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=26449"},"modified":"2023-05-30T13:22:38","modified_gmt":"2023-05-30T07:52:38","slug":"python-heapq","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-heapq\/","title":{"rendered":"Python Heapq: Boost Your Efficiency with Heap Operations!"},"content":{"rendered":"\n<p>The heapq module is a module for Python that implements heaps with priority queues. This post will show you how to use the heapq module, including how to create your own heaps and implement them with priority queues.<\/p>\n\n\n\n<p>Priority queues are one of the data structures for stacks and queues. Heapq helps to execute such queues. In other words, the module suits situations where you need a stable and efficient implementation of priority queues.<\/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-heapq\/#Priority_Queue\" >Priority Queue<\/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-heapq\/#What_is_heapq_in_Python\" >What is heapq 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-heapq\/#Functions_of_heapq_module\" >Functions of 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-4\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Heapify\" >Heapify<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Heapreplace\" >Heapreplace<\/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-heapq\/#Heappop\" >Heappop<\/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-heapq\/#Heappush\" >Heappush<\/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-heapq\/#heapq_python_comparator\" >heapq python comparator<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#heapq_%E2%80%98not_supported_between_instances\" >heapq &#8216;not supported between instances&#8217;<\/a><\/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-heapq\/#Built-in_heapq\" >Built-in heapq<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Check_for_a_node_in_heapq\" >Check for a node in heapq<\/a><\/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-heapq\/#Change_priority_in_heapq\" >Change priority in heapq<\/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-heapq\/#Sorted_heapq\" >Sorted heapq<\/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-heapq\/#Heapq_time_complexity\" >Heapq time complexity<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#python_heapq_custom_comparator\" >python heapq custom comparator<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Python_heapq_Vs_Priority_queue\" >Python heapq Vs Priority queue<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#python_heapq_tuple\" >python heapq tuple<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#FAQs\" >FAQs<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#Trending_Python_Articles\" >Trending Python Articles<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"h-priority-queue\"><span class=\"ez-toc-section\" id=\"Priority_Queue\"><\/span>Priority Queue <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The PriorityQueue, or heapq module in Python, is a data structure for dynamic priority queues with O(1) lookup time. It generalizes the singly linked list to allow for multiple elements with different access times. This data structure can be used to implement priority queue algorithms and maintainers.<\/p>\n\n\n\n<p>A priority queue is an ordered list where each element has a value and must be smaller than or equal to the element before it and greater than or equal to the element after it. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-what-is-heapq-in-python\"><span class=\"ez-toc-section\" id=\"What_is_heapq_in_Python\"><\/span>What is heapq in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Heapq, the heap module in Python, offers a lot of functionality for building data structures. It is similar to the Queue module in that it allows you to build data structures on top of itself and add elements one by one. Heapq also has some additional functionality that Queue does not have, like the ability to iterate over items in the Queue and support multi-level queues.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"940\" height=\"788\" src=\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/03\/20230306_235127_0000.png\" alt=\"heapq in python\" class=\"wp-image-26554\" srcset=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/03\/20230306_235127_0000.png 940w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/03\/20230306_235127_0000-300x251.png 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/03\/20230306_235127_0000-768x644.png 768w\" sizes=\"(max-width: 940px) 100vw, 940px\" \/><figcaption class=\"wp-element-caption\"><em>Python heapq<\/em><\/figcaption><\/figure>\n\n\n\n<p>Heapq was in Python 3.3 version. It is in all versions after 3.3.<\/p>\n\n\n\n<p>The most common use case for heapq is to build a priority queue (also known as a deque). <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-functions-of-heapq-module\"><span class=\"ez-toc-section\" id=\"Functions_of_heapq_module\"><\/span>Functions of heapq module<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>heapq have multiple functions like heapify, heapreplace, heappop, heappush, etc.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-heapify\"><span class=\"ez-toc-section\" id=\"Heapify\"><\/span>Heapify<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It helps to create a heap out of a list. It will arrange and put the smallest member of the list in the first position. Let&#8217;s look at the following example to get a better understanding :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nH = &#x5B;2,1,4,3,5]\n# Use heapify to rearrange the elements\nheapq.heapify(H)\nprint(H)\n<\/pre><\/div>\n\n\n<p>Hence, the output will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;1, 2, 4, 3, 5]\n#So,heapify brought the smallest number,1 to the beginning \n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-heapreplace\"><span class=\"ez-toc-section\" id=\"Heapreplace\"><\/span>Heapreplace<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It replaces the smallest element with the number you have entered as an argument.  There is no particular order\/ place where the element will be inserted. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nH1 = &#x5B;2,1,4,3,5]\nheapq.heapify(H1)\nheapq.heapreplace(H1,2)\nprint(H1)\n#Output :\n#&#x5B;2, 2, 4, 3, 5]\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-heappop\"><span class=\"ez-toc-section\" id=\"Heappop\"><\/span>Heappop<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It is used to pop the first unwanted element from the list. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nH1 = &#x5B;2,1,4,3,5]\nheapq.heappop(H1)\nprint(H1)\n<\/pre><\/div>\n\n\n<p>The output will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;1, 3, 4, 5]\n<\/pre><\/div>\n\n\n<p>You can also use heapify function followed by heappop to pop the smallest element at the first index. Look at this example :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nH1 = &#x5B;2,1,4,3,5]\nheapq.heapify(H1)\nheapq.heappop(H1)\nprint(H1)\n#output: &#x5B;2, 3, 4, 5]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-heappush\"><span class=\"ez-toc-section\" id=\"Heappush\"><\/span>Heappush<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>As the name suggests, it helps to push a new number into the heap or add a new number to the list.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nHEAP = &#x5B;2,1,4,3,5]\nheapq.heappush(HEAP,10)\nprint(HEAP)\n#OUTPUT: &#x5B;2, 1, 4, 3, 5, 10]\n<\/pre><\/div>\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-juliett monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-image\"><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_.webp 1200w \" alt=\"[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date\" \/><\/a><\/div><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><span class=\"monsterinsights-inline-popular-posts-border\" ><\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\">[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-heapq-python-comparator\"><span class=\"ez-toc-section\" id=\"heapq_python_comparator\"><\/span>heapq python comparator<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Only lists and tuples work with heapq. There might be a case when you have to work with some other data type, like a dictionary.  So, in this case, we will convert the dictionary to a tuple.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq as hq \nNewdict= {'z': 'Daman and Diu', 'b': 'Chandigarh', 'a': 'Punjab', 'm': 'Sikkim', 'c': 'Goa'} \n\n#change dictionary to list\nNewlist = &#x5B;(k, v) for k, v in my_dict.items()] \nprint(&quot;List format :&quot;, Newlist) \n#Make a heap from the list\nhq.heapify(Newlist) \nprint(&quot;Heap format with list:&quot;, Newlist) \n# Output the answer as dictionary(original)\nNewdict = dict(Newlist) \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-heapq-not-supported-between-instances\"><span class=\"ez-toc-section\" id=\"heapq_%E2%80%98not_supported_between_instances\"><\/span>heapq &#8216;not supported between instances&#8217; <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We know that a heapq works with lists and tuples. This issue arises when the &lt;= operator used by heapq can&#8217;t make a comparison between the tuple or lost components. <\/p>\n\n\n\n<p>There might arise a situation when the tuple components of the tuples that have to be compared are NOT DIFFERENT.  In this situation, we will get an error. For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nA = (5, object())\nB= (2, object())\nC= (5, object())\nprint(A&lt;= B) #FALSE\nprint(A&lt;= C) #error\n<\/pre><\/div>\n\n\n<p>The operator compares the first two components usually. To get over this issue, we can use a comparison operator directly, like  __lt__(self, other) for &lt; or __le__(self, other) for &lt;= and others.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-built-in-heapq\"><span class=\"ez-toc-section\" id=\"Built-in_heapq\"><\/span>Built-in heapq<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The heapq module is a built-in module in Python. This means that the functionalities of heapq are predefined. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-check-for-a-node-in-heapq\"><span class=\"ez-toc-section\" id=\"Check_for_a_node_in_heapq\"><\/span>Check for a node in heapq<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Use any to find if an element is present in a heap. The following example will suffice-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmyheap = &#x5B;]\nX= (321,4)\nY = (258,3)\nheapq.heappush(myheap,X)\nheapq.heappush(myheap,Y)\nnode = 4\nif any(node in i for i in myheap):\n       print('Found')\n\n#we used the heappush function whose use is stated above\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-change-priority-in-heapq\"><span class=\"ez-toc-section\" id=\"Change_priority_in_heapq\"><\/span>Change priority in heapq<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can easily change the priority of the element in heapq. Update it the way you do with lists because originally, heapq is formed of lists and tuples only. This piece of code will make it easy to interpret updating priority in heapq.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nmyheap = &#x5B;]\nheapq.heappush(myheap, (2, &quot;Books&quot;))\nheapq.heappush(myheap, (4, &quot;Laptop&quot;))\nheapq.heappush(myheap, (5, &quot;Pencils&quot;))\nprint(myheap)\nmyheap&#x5B;0] = (3, 'Pencils')\nprint(myheap)\nheapq.heapify(myheap)\nprint(myheap)\n<\/pre><\/div>\n\n\n<p>Push the Priority key and value pair into the heap. Now, if you want to change the priority of an element, you can just use the index and update it. Simply equate the new priority and use heapify() function to store this in heap format. Let&#8217;s look at the output. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;(2, 'Books'), (4, 'Laptop'), (5, 'Pencils')]\n&#x5B;(3, 'Pencils'), (4, 'Laptop'), (5, 'Pencils')]\n&#x5B;(3, 'Pencils'), (4, 'Laptop'), (5, 'Pencils')]\n\n<\/pre><\/div>\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-golf monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Popular now<\/span><span class=\"monsterinsights-inline-popular-posts-border\" ><\/span><span class=\"monsterinsights-inline-popular-posts-border-2\" ><\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\">[Fixed] nameerror: name Unicode is not defined<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-sorted-heapq\"><span class=\"ez-toc-section\" id=\"Sorted_heapq\"><\/span>Sorted heapq <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Use the sorted function to sort the heap. If you want it in reverse order, you can use the reverse argument as True.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport heapq\nAheap = &#x5B;]\nheapq.heappush(Aheap, (5, &quot;A&quot;))\nheapq.heappush(Aheap, (1, &quot;B&quot;))\nheapq.heappush(Aheap, (9, &quot;C&quot;))\nheapq.heappush(Aheap, (4, &quot;D&quot;))\nprint(sorted(Aheap, reverse=True))\n#for reverse order\n<\/pre><\/div>\n\n\n<p>Hence, the output is:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;(9, 'C'), (5, 'A'), (4, 'D'), (1, 'B')]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-heapq-time-complexity\"><span class=\"ez-toc-section\" id=\"Heapq_time_complexity\"><\/span>Heapq time complexity<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The complexity of the heapify function is O(logn).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-heapq-custom-comparator\"><span class=\"ez-toc-section\" id=\"python_heapq_custom_comparator\"><\/span>python heapq custom comparator<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Python has a heapq module that allows you to work with sorted collections of objects. The heapq module has a custom comparator, which is useful for sorting data in Python. This is convenient if you want to implement your own custom data structure but still want to be able to use Heapq for efficient in-memory operations. So, it is a custom comparator that does not use the default heapq.bucket_by_key function, but instead uses a custom one.  Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom heapq import Heapq\nmy_cmp = lambda x, y: (x &gt; y) != None \nprint(Heapq(&#x5B;1, 2, 3], my_cmp))\n# &#x5B;True, True, False]\n<\/pre><\/div>\n\n\n<p>When comparing two values in heapq, it will compare them using the &lt; operator. This means that when you use my_cmp as a comparator for the elements of a list object, it will look at the first element of the list object and compare it to the second element. If they are equal, then they are considered equal. If they are unequal, then they are not considered equal.<\/p>\n\n\n\n<p>So let&#8217;s say that we want to check whether an integer is greater than its square root. In this case, we need to write another function that does what my_cmp does but for integers instead of strings!<\/p>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-alpha monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\">[Solved] runtimeerror: cuda error: invalid device ordinal<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-heapq-vs-priority-queue\"><span class=\"ez-toc-section\" id=\"Python_heapq_Vs_Priority_queue\"><\/span>Python heapq Vs Priority queue<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Heapq and <span style=\"text-decoration: underline;\"><strong><a href=\"http:\/\/www.pythonpool.com\/python-priority-queue\/\" target=\"_blank\" rel=\"noreferrer noopener\">priority queue<\/a><\/strong><\/span> are two of the most common collections in Python. They are both used for sorting and searching, but they are different. Let&#8217;s look at the differences offered by heapq and priority queue.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th class=\"has-text-align-center\" data-align=\"center\"><strong>heapq<\/strong><\/th><th class=\"has-text-align-center\" data-align=\"center\"><strong>priority queue<\/strong><\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">Heapq is a Python data structure that implements a binary heap data structure. <\/td><td class=\"has-text-align-center\" data-align=\"center\">A priority queue is a collection of objects that can be sorted from highest to lowest value.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> It can be used to implement a priority queue, which is a collection of objects that can be sorted according to their values.<\/td><td class=\"has-text-align-center\" data-align=\"center\">It is used for solving problems like finding the smallest number or item among a set of items or finding the largest number or item among a set of items. The quality of an algorithm determines how fast it can find an item in a priority queue.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">Heaps can automatically remove duplicates when they are added or removed from the data set.<\/td><td class=\"has-text-align-center\" data-align=\"center\">A prioritizer cannot do this because it does not know where duplicate elements exist in its data set until they have been added or removed from the original list.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-heapq-tuple\"><span class=\"ez-toc-section\" id=\"python_heapq_tuple\"><\/span>python heapq tuple<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Python has a built-in module called heapq that you can use to create tuples. A tuple is a data structure that consists of two or more values stored in memory at once, ordered in a particular way. Python&#8217;s heapq is a higher-level way of handling tuples. Heapq is a way to organize and work with Python dictionaries and lists into tuples. It is similar to the way you might organize your data in a spreadsheet, where you have cells that are rows and columns. <\/p>\n\n\n\n<p>The syntax for creating a tuple is as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n(value1, value2, ..., valueN)\n<\/pre><\/div>\n\n\n<p>The above example shows how to create an empty tuple using three elements: value1, value2, and valueN. If we want to add more values to the tuple, we can add more elements after the opening parenthesis and separate them with commas. For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n(1,&quot;Hello&quot;, 2)\n<\/pre><\/div>\n\n\n<p>A heapq object allows you to convert any Python object into an ordered set of values in such a way that each value can be accessed using its key. Heapq objects allow for efficient access using hashing functions. Each key looks up its value by name.  means that no lookup operations are required for accessing elements with equal keys (though some may still be required for equal keys not present within the set). Heapq objects are constructed from dictionaries or lists by calling the function get_heapq()<\/p>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-alpha monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method\/\">[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-faqs\"><span class=\"ez-toc-section\" id=\"FAQs\"><\/span>FAQs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1677791336182\"><strong class=\"schema-faq-question\">Why is Priority Queue different from heapq?<\/strong> <p class=\"schema-faq-answer\">The first one doesn&#8217;t change the Queue, but heapq works on the original structure.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1684059705591\"><strong class=\"schema-faq-question\">What is the default Heapq in Python?<\/strong> <p class=\"schema-faq-answer\"><a href=\"http:\/\/www.pythonpool.com\/min-heap-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">min heap<\/a> is the default heapq in Python. <\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1684059736426\"><strong class=\"schema-faq-question\">Is Python Heapq sorted?<\/strong> <p class=\"schema-faq-answer\">Python&#8217;s heapq function sorts the items of a sequence in ascending order. However, this is only true if you pass it as an ordered list and not a list of arbitrary objects. If you try to sort a list of arbitrary objects, you&#8217;ll get an error message.<\/p> <\/div> <\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this tutorial, we discussed the Python heapq module in detail. By now, you must have got a fair idea of how the module works, its functions, and the usage of the priority queue in Python. <\/p>\n\n\n<div class=\"monsterinsights-widget-popular-posts monsterinsights-widget-popular-posts-delta monsterinsights-popular-posts-styled monsterinsights-widget-popular-posts-columns-2\"><h2 class=\"monsterinsights-widget-popular-posts-widget-title\"><span class=\"ez-toc-section\" id=\"Trending_Python_Articles\"><\/span>Trending Python Articles<span class=\"ez-toc-section-end\"><\/span><\/h2><ul class=\"monsterinsights-widget-popular-posts-list\"><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_.webp 1200w \" alt=\"[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 11, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined.webp 1200w \" alt=\"[Fixed] nameerror: name Unicode is not defined\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] nameerror: name Unicode is not defined<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal.webp 1200w \" alt=\"[Solved] runtimeerror: cuda error: invalid device ordinal\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Solved] runtimeerror: cuda error: invalid device ordinal<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method.webp 1200w \" alt=\"[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><\/ul><\/div><p><\/p>","protected":false},"excerpt":{"rendered":"<p>The heapq module is a module for Python that implements heaps with priority queues. This post will show you how to use the heapq module, &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Python Heapq: Boost Your Efficiency with Heap Operations!\" class=\"read-more button\" href=\"https:\/\/www.pythonpool.com\/python-heapq\/#more-26449\" aria-label=\"More on Python Heapq: Boost Your Efficiency with Heap Operations!\">Read more<\/a><\/p>\n","protected":false},"author":38,"featured_media":27908,"comment_status":"open","ping_status":"closed","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":[5799,5802,1587,5801,5800],"class_list":["post-26449","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-python-heapq-example","tag-python-heapq-key","tag-python-heapq-max-heap","tag-python-heapq-peek","tag-python-heapq-tuple","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>Python Heapq: Boost Your Efficiency with Heap Operations!<\/title>\n<meta name=\"description\" content=\"Learn how to implement the heapq module in python with this article. Get to know what differentiates a heapq from a priority queue.\" \/>\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-heapq\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Heapq: Boost Your Efficiency with Heap Operations!\" \/>\n<meta property=\"og:description\" content=\"The heapq module is a module for Python that implements heaps with priority queues. This post will show you how to use the heapq module, including how to\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-heapq\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-30T07:52:31+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-30T07:52:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"Namrata Gulati\" \/>\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=\"Namrata Gulati\" \/>\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-heapq\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/\"},\"author\":{\"name\":\"Namrata Gulati\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/294338f378f0853e6af4ca4a5a907ea6\"},\"headline\":\"Python Heapq: Boost Your Efficiency with Heap Operations!\",\"datePublished\":\"2023-05-30T07:52:31+00:00\",\"dateModified\":\"2023-05-30T07:52:38+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/\"},\"wordCount\":1466,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp\",\"keywords\":[\"python heapq example\",\"python heapq key\",\"python heapq max heap\",\"python heapq peek\",\"python heapq tuple\"],\"articleSection\":[\"Tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.pythonpool.com\/python-heapq\/#respond\"]}]},{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/\",\"url\":\"https:\/\/www.pythonpool.com\/python-heapq\/\",\"name\":\"Python Heapq: Boost Your Efficiency with Heap Operations!\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp\",\"datePublished\":\"2023-05-30T07:52:31+00:00\",\"dateModified\":\"2023-05-30T07:52:38+00:00\",\"description\":\"Learn how to implement the heapq module in python with this article. Get to know what differentiates a heapq from a priority queue.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#breadcrumb\"},\"mainEntity\":[{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182\"},{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591\"},{\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426\"}],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pythonpool.com\/python-heapq\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage\",\"url\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp\",\"contentUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp\",\"width\":1200,\"height\":628,\"caption\":\"python heapq\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pythonpool.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Heapq: Boost Your Efficiency with Heap Operations!\"}]},{\"@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\/294338f378f0853e6af4ca4a5a907ea6\",\"name\":\"Namrata Gulati\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/19c5e6bfbc6202d4017b79f726b2ad5e520491d67ff428a87c071afef23ecd89?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/19c5e6bfbc6202d4017b79f726b2ad5e520491d67ff428a87c071afef23ecd89?s=96&d=wavatar&r=g\",\"caption\":\"Namrata Gulati\"}},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182\",\"position\":1,\"url\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182\",\"name\":\"Why is Priority Queue different from heapq?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"The first one doesn't change the Queue, but heapq works on the original structure.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591\",\"position\":2,\"url\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591\",\"name\":\"What is the default Heapq in Python?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<a href=\\\"http:\/\/www.pythonpool.com\/min-heap-python\/\\\" target=\\\"_blank\\\" rel=\\\"noreferrer noopener\\\">min heap<\/a> is the default heapq in Python. \",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426\",\"position\":3,\"url\":\"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426\",\"name\":\"Is Python Heapq sorted?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Python's heapq function sorts the items of a sequence in ascending order. However, this is only true if you pass it as an ordered list and not a list of arbitrary objects. If you try to sort a list of arbitrary objects, you'll get an error message.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Python Heapq: Boost Your Efficiency with Heap Operations!","description":"Learn how to implement the heapq module in python with this article. Get to know what differentiates a heapq from a priority queue.","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-heapq\/","og_locale":"en_US","og_type":"article","og_title":"Python Heapq: Boost Your Efficiency with Heap Operations!","og_description":"The heapq module is a module for Python that implements heaps with priority queues. This post will show you how to use the heapq module, including how to","og_url":"https:\/\/www.pythonpool.com\/python-heapq\/","og_site_name":"Python Pool","article_published_time":"2023-05-30T07:52:31+00:00","article_modified_time":"2023-05-30T07:52:38+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp","type":"image\/webp"}],"author":"Namrata Gulati","twitter_card":"summary_large_image","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Namrata Gulati","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/"},"author":{"name":"Namrata Gulati","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/294338f378f0853e6af4ca4a5a907ea6"},"headline":"Python Heapq: Boost Your Efficiency with Heap Operations!","datePublished":"2023-05-30T07:52:31+00:00","dateModified":"2023-05-30T07:52:38+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/"},"wordCount":1466,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp","keywords":["python heapq example","python heapq key","python heapq max heap","python heapq peek","python heapq tuple"],"articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-heapq\/#respond"]}]},{"@type":["WebPage","FAQPage"],"@id":"https:\/\/www.pythonpool.com\/python-heapq\/","url":"https:\/\/www.pythonpool.com\/python-heapq\/","name":"Python Heapq: Boost Your Efficiency with Heap Operations!","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp","datePublished":"2023-05-30T07:52:31+00:00","dateModified":"2023-05-30T07:52:38+00:00","description":"Learn how to implement the heapq module in python with this article. Get to know what differentiates a heapq from a priority queue.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#breadcrumb"},"mainEntity":[{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182"},{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591"},{"@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426"}],"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-heapq\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2023\/05\/python-heapq.webp","width":1200,"height":628,"caption":"python heapq"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Python Heapq: Boost Your Efficiency with Heap Operations!"}]},{"@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\/294338f378f0853e6af4ca4a5a907ea6","name":"Namrata Gulati","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/19c5e6bfbc6202d4017b79f726b2ad5e520491d67ff428a87c071afef23ecd89?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/19c5e6bfbc6202d4017b79f726b2ad5e520491d67ff428a87c071afef23ecd89?s=96&d=wavatar&r=g","caption":"Namrata Gulati"}},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182","position":1,"url":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1677791336182","name":"Why is Priority Queue different from heapq?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"The first one doesn't change the Queue, but heapq works on the original structure.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591","position":2,"url":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059705591","name":"What is the default Heapq in Python?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<a href=\"http:\/\/www.pythonpool.com\/min-heap-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">min heap<\/a> is the default heapq in Python. ","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426","position":3,"url":"https:\/\/www.pythonpool.com\/python-heapq\/#faq-question-1684059736426","name":"Is Python Heapq sorted?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"Python's heapq function sorts the items of a sequence in ascending order. However, this is only true if you pass it as an ordered list and not a list of arbitrary objects. If you try to sort a list of arbitrary objects, you'll get an error message.","inLanguage":"en-US"},"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/26449","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\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=26449"}],"version-history":[{"count":90,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/26449\/revisions"}],"predecessor-version":[{"id":27909,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/26449\/revisions\/27909"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/27908"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=26449"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=26449"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=26449"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}