{"id":4529,"date":"2022-06-13T21:18:00","date_gmt":"2022-06-14T02:18:00","guid":{"rendered":"https:\/\/wanderin.dev\/?p=4529"},"modified":"2024-10-06T10:10:07","modified_gmt":"2024-10-06T15:10:07","slug":"a-queue-implementation-in-python","status":"publish","type":"post","link":"https:\/\/javierfeliu.me\/python-interview\/a-queue-implementation-in-python\/","title":{"rendered":"A Queue Implementation in Python"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\" id=\"h-about-this-article\">About this article<\/h2>\n\n\n\n<p>In this article, I&#8217;ll explore the <strong>queue<\/strong>, a linear data structure we can quickly implement in Python.&nbsp;<\/p>\n\n\n\n<p>This post is the second in a miniseries exploring the implementation of linear data structures. I based the series on my notes while studying for a Python technical interview.<\/p>\n\n\n\n<p>For quick access, here is the list of posts on this series:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><a href=\"https:\/\/javierfeliu.me\/python-interview\/a-stack-implementation-in-python\/\">A Stack Implementation in Python<\/a> <\/li><li>A Queue Implementation in Python (this article)<\/li><li><a href=\"https:\/\/javierfeliu.me\/python-interview\/a-priority-queue-implementation-in-python\/\">A Priority Queue Implementation in Python<\/a><\/li><li><a href=\"https:\/\/javierfeliu.me\/python-interview\/link-lists-implementations-in-python\/\">Linked Lists Implementations In Python<\/a><\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-introduction-to-queues\">Introduction to queues<\/h2>\n\n\n\n<p>In computer science, a queue is an abstract data type serving as a collection of items maintained in a sequence where <strong>items are added at one end and removed at the other<\/strong>. The operations of a queue make it a <strong>first-in, first-out<\/strong> data structure (FIFO).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-uses-for-queue\">Uses for queue<\/h2>\n\n\n\n<p>In programming, you can use queues to implement applications and functionality that require FIFO data access. Some examples might be:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The keyboard buffer.<\/li><li>The printer queue.<\/li><li>The mail queue.<\/li><li>IO buffers.<\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-queue-methods\">Queue methods<\/h2>\n\n\n\n<p>Most queue implementations have the following methods:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>queue.enqueue(x):&nbsp;<\/strong>adds an element to the back of the queue.<\/li><li><strong>queue.dequeue():<\/strong>&nbsp;returns and removes the element at the front of the queue.<\/li><li><strong>queue.peek():<\/strong>&nbsp;returns the element at the front of the queue.<\/li><li><strong>queue.size():<\/strong>&nbsp;returns the number of elements in the queue.<\/li><li><strong>queue.is_empty():<\/strong>&nbsp;returns True is the queue is empty.<\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-queue-implementation\">Queue implementation<\/h2>\n\n\n\n<p>Python implements <strong>multi-producer, multi-consumer queues in the Lib\/queue.py module<\/strong>. For production applications requiring queues, you should import and use those implementations.<\/p>\n\n\n\n<p>Since our purpose with this article is to study queues as preparation for a technical interview, we&#8217;ll do our implementation using the <strong>double-ended queue (deque)<\/strong> available from the collections module in Python. The reason for using deques instead of other data types like lists are:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>In deques, <strong>appends and poplelfts<\/strong> are memory efficient and thread-safe.<\/li><li>In deques, <strong>appends and poplelfts have constant time complexity O(1)<\/strong><\/li><\/ol>\n\n\n\n<p>Let&#8217;s go over our queue implementation using deques.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-the-queue-class\">The Queue class<\/h3>\n\n\n\n<p>We define a Queue class with a constructor that instantiates an empty deque and a __str__ method that returns a readable representation of the queue object. At the top of the module, we must import deque from collections.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/55f54e1cc534038f40fbbee1d38e120a.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-queue-is_empty\">queue.is_empty():<\/h3>\n\n\n\n<p>The is_empty method returns True if the queue is empty.<\/p>\n\n\n\n<p>This method has a constant time complexity O(1).<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/8e603d3b145074b6ae01e53a646139d2.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-queue-enqueue-item\">queue.enqueue(item)<\/h3>\n\n\n\n<p>The enqueue method adds an item to the back of the queue, using the append method from deque.<\/p>\n\n\n\n<p>This method has a constant time complexity O(1).<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/ac6a71356ef721e0b7118c4390ca6179.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-queue-dequeue\">queue.dequeue()<\/h3>\n\n\n\n<p>The dequeue method returns and removes the item at the front of the queue, using the popleft method from deque. To avoid getting an IndexError when popping from an empty queue, we first check if it is empty and return None.<\/p>\n\n\n\n<p>This method has a constant time complexity O(1).<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/8b6505785a519673f81bff2fc76d2b5c.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-queue-peek\">queue.peek()<\/h3>\n\n\n\n<p>The peek method returns the item at the front of the queue (index 0). As with dequeue, we need to return None if the queue is empty to avoid an IndexError.<\/p>\n\n\n\n<p>This method has a constant time complexity O(1).<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/1bab7ae37b7e98043a6a4ccb01f38e0d.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-queue-size\">queue.size()<\/h3>\n\n\n\n<p>The size method returns the length of the queue.<\/p>\n\n\n\n<p>This method has a constant time complexity O(1).<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/bff32c0fc9121cc189ec560650153c4d.js\"><\/script>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-the-full-implementation\">The full implementation<\/h3>\n\n\n\n<p>Below is the full implementation and some test cases:<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/wanderindev\/b514c285061206b8f71cfe9d6fad4435.js\"><\/script>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2>\n\n\n\n<p>In this article, we implemented a <strong>queue <\/strong>in Python. The queue is a linear data structure useful when accessing data in a first-in, first-out fashion. Our implementation uses deque, allowing for thread-safe, memory efficient, and constant time enqueues and dequeues.<\/p>\n\n\n\n<p>In the <a href=\"https:\/\/javierfeliu.me\/python-interview\/a-priority-queue-implementation-in-python\/\">next article<\/a>, we&#8217;ll explore the priority queue.  See you there!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-references\">References<\/h2>\n\n\n\n<p><a target=\"_blank\" href=\"https:\/\/en.wikipedia.org\/wiki\/Queue_(abstract_data_type)\" rel=\"noreferrer noopener\">Wikipedia &#8211; Queue (abstract data type)<\/a><\/p>\n\n\n\n<p><a target=\"_blank\" href=\"https:\/\/www.geeksforgeeks.org\/applications-of-queue-data-structure\/\" rel=\"noreferrer noopener\">GeeksForGeeks &#8211; Applications of Queue Data Structure<\/a><\/p>\n\n\n\n<p><a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/collections.html#collections.deque\" rel=\"noreferrer noopener\">Python Documentation &#8211; deque<\/a><\/p>\n\n\n\n<p><a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/queue.html\" rel=\"noreferrer noopener\">Python Documentation &#8211; queue &#8211; A synchronized queue class<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we implement a queue in Python using deque.  We also explore queues&#8217; uses, typical methods, and time complexity.<\/p>\n<p>This article is the second in a miniseries exploring linear data structures in Python.<\/p>\n","protected":false},"author":152069353,"featured_media":4621,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","footnotes":""},"categories":[4504529,4504527],"tags":[4504532,4504531],"class_list":["post-4529","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linear-data-structures-in-python","category-python-interview","tag-linear-data-structures","tag-python-interview"],"jetpack_featured_media_url":"https:\/\/javierfeliu.me\/wp-content\/uploads\/2022\/06\/7.png","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/posts\/4529","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/users\/152069353"}],"replies":[{"embeddable":true,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/comments?post=4529"}],"version-history":[{"count":18,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/posts\/4529\/revisions"}],"predecessor-version":[{"id":4740,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/posts\/4529\/revisions\/4740"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/media\/4621"}],"wp:attachment":[{"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/media?parent=4529"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/categories?post=4529"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/javierfeliu.me\/wp-json\/wp\/v2\/tags?post=4529"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}