×

Python Queue

Python Queue

There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for your turn in some store, we all are pretty familiar with the concept of the Queue as we wait for our services. In the same way, the queue in data structure plays a significant role in data science and computer engineering. The thing which makes the Queue unique is its functionalities. Based on the FIFO (First-In-First-Out) model, the data elements are allowed at one end and removed from the other one. But before we jump into the depth of the Queue, let’s discuss – What do we understand by the Queue in Python?

Queue in Python

The Queue in Python is an important concept in Data Structure. The Queue is a data structure where the data elements are organized in a linear manner. Moreover, the Queue in Python helps in controlling the flow of the tasks.

Like the Stack, the Queue is a linear data structure where the data elements are stored with the FIFO (First-In-First-Out) Principle. Its property implies that the least recently added data elements would be removed first. Let’s take a real-life example, where few customers are standing in Queue at the bill counter and wait for their turn to come. The shopkeeper is dealing with each customer one after one. Thus, who comes first would be served first.

Now, let’s discuss some operations associated with the Queue data structure. Have a look at a schematic diagram representing a Queue shown below:

Python Queue

Some of the operations associated with Queue and their descriptions are listed as follow:

S. No.OperationDescription
1FrontThe Front returns the first data element from the Queue – Time Complexity: O(1)
2RearThe Rear returns the last data element from the Queue – Time Complexity: O(1)
3EnqueueThe Enqueue is used to add the data element to the Queue. However, the condition is said to be overflowing if the Queue appears to be full – Time Complexity: O(1)
4DequeueThe Dequeue is used to remove the data element from the Queue. The data elements in the Queue are popped out in the same manner as they as pushed in. However, the condition is said to be underflowing if the Queue appears to be empty – Time Complexity: O(1)

Queue Implementation in Python

Python provides several methods for implementing a Queue. In this section, we will discuss the data structures and modules available in the Python library that are useful in implementing a Queue. Some of the methods used in Queue Implementation are given below:

  1. list
  2. queue.Queue
  3. collections.deque

Queue Implementation using List

The list is a built-in Python data structure available that can help in implementing a Queue. The list uses the functions like append() and pop() instead of enqueue() and dequeue() respectively. However, the list is quite slow to fulfill the purpose as the insertion or removal of a data element at the start needs a shift in all the other data elements by one, requiring the O(n) time.

Here is an example given below that illustrates the Queue's implementation using list. 

# Initializing a list
 # as the Queue
 my_queue = [] 
 # Adding some data elements
 # to my_queue
 my_queue.append('Apple')      
 my_queue.append('Banana')
 my_queue.append('Mango')
 my_queue.append('Orange')
 # Printing the data
 # elements of the Queue
 print(my_queue)                    
 # Removing the data
 # elements from
 # Zeroth Index
 print(my_queue.pop(0))             
 print(my_queue.pop(0))
 print(my_queue.pop(0))
 print(my_queue.pop(0))
 # Since the Queue is empty, it will display the error.
 print(my_queue.pop(0))                   

Output:

['Apple', 'Banana', 'Mango', 'Orange']
 'Apple'
 'Banana'
 'Mango'
 'Orange'
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 IndexError: pop from empty list 

Explanation:

In the above code, we have initialized a list as the Queue and inserted a few data elements such as apple, banana, mango and orange in it with the append() function. Then, we have used the pop() function specifying the data element's zeroth position we wanted to remove.

Thus, the above list is behaving like a Queue. Moreover, in the last line of code, we have again used the pop() function on an empty queue that will return an Index Error stating the list is empty.

Queue Implementation using Classes

Using the collections.deque Class

The deque class in Python is used for implementing a double-ended queue supporting the insertion and elimination of data elements from either end in Time Complexity: O(1) (non-amortized).

We can implement a Queue in Python with the help of the deque class provided by the collections module. Since the deque class provides a quicker insert and remove operations, it becomes preferable over the list. However, the deque class uses append(), and popleft() functions instead of the enqueue and deque. Let’s see an example based on this class.

# importing the deque class from collections module
 from collections import deque
 # initializing a queue
 my_queue = deque()
 # inserting data elements to the queue
 my_queue.append('Apple')
 my_queue.append('Mango')
 my_queue.append('Banana')
 my_queue.append('Orange')
 my_queue.append('Kiwi')
 # printing the queue
 print(my_queue)
 # removing the data elements
 print(my_queue.popleft())
 print(my_queue.popleft())
 print(my_queue.popleft())
 print(my_queue.popleft())
 print(my_queue.popleft())
 # Since the queue is empty, it will return and Index error
 print(my_queue.popleft()) 

Output:

deque(['Apple', 'Mango', 'Banana', 'Orange', 'Kiwi'])
 Apple
 Mango
 Banana
 Orange
 Kiwi 
 Traceback (most recent call last):
   File "D:\Python\queue.py", line 18, in <module>
     print(my_queue.popleft())
 IndexError: pop from an empty deque 

Explanation:

In the above example, we have imported the deque class from the collections module and initialize a queue using the class. We have then used the append() function to insert the data elements such as Apple, Mango, Banana, Orange, and Kiwi into the queue. Once the queue is created, we have used the popleft() function to remove data elements one by one in the systematic queue order. However, the function will return an error if the queue gets empty, as in the last example.

Using the queue.Queue class

Python provides a built-in queue module that provides access to its Queue class and implements a queue. The queue.Queue(maxsize) class is used to initialize a variable to a maximum size of maxsize. If maxsize is defined as zero ‘0’, it will create an infinite queue. Moreover, this Queue is based on the FIFO principle.

Some of the functions used in this module are listed in the following table:

S. No.FunctionDescription
1maxsize()The maxsize() function is used to define the number of items that are allowed in the queue.
2full()The full() function returns a Boolean value depending on whether the queue is full or not. It returns True if the data elements are equal to the maxsize of the queue. However, it never returns True if the queue is initialized with the maxsize = 0 (i.e., default).
3empty()The empty() function also returns a Boolean value depending on whether the queue is empty or not. Thus, it returns True if the queue is empty or otherwise False.
4put()The put() function is used to insert an item or data element into the queue. However, it waits until a free slot is available if in case the queue is full.
5get()The get() function is used to remove and return an item or data element from the queue. However, it waits for the item until it’s available if in case the queue is empty.
6put_nowait(item)The put_nowait() function is used to insert an item or data element into the queue without blocking or waiting. Moreover, it returns QueueFull if there is no free slot available immediately in the queue.
7get_nowait()The get_nowait() function is used to remove and return an item or data element from the queue without blocking or waiting. Moreover, it returns QueueEmpty if in case the queue is empty.
8qsize()The qsize() function is used to return the total number of items available in the queue.

Let’s see an example based on this class.

# importing the Queue class from queue module
 from queue import Queue
 # Initializing a queue
 my_queue = Queue(maxsize = 4)
 # printing the present size of the queue
 print(my_queue.qsize()) 
 # Adding the data element to queue
 my_queue.put('Apple')
 my_queue.put('Mango')
 my_queue.put('Banana')
 my_queue.put('Orange')
 # Return Boolean for Full Queue 
 print("\nThe Queue is Full: ", my_queue.full()) 
 # Removing the data element from queue
 print("\nData Elements dequeued from the queue:")
 print(my_queue.get())
 print(my_queue.get())
 print(my_queue.get())
 print(my_queue.get())
 # Return Boolean for Empty Queue
 print("\nThe Queue is Empty: ", my_queue.empty())
 my_queue.put("Kiwi")
 print("\nThe Queue is Empty: ", my_queue.empty()) 
 print("The Queue is Full: ", my_queue.full()) 

Output:

0
 The Queue is Full: True
 Data Elements dequeued from the queue:
 Apple
 Mango
 Banana
 Orange
 The Queue is Empty: True
 The Queue is Empty: False
 The Queue is Full: False 

Related Topics

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Python Skyline

Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.