A Queue in Python is a linear data structure that stores items in a First In, First Out (FIFO) manner. With the help of a queue in Python, we can control the flow of our tasks. In this article, we will explore the will understand the particle details on this topic.
Table of Contents
What is Queue in Python?
A queue is an abstract data type used for storing and managing data in a specific order. It has a rear (where elements are added) and a front (where elements are removed). Queues can be implemented using arrays or linked lists and support multi-producer, multi-consumer scenarios, making them a useful data structure in programming.
Types of Python Queue
There are Four types of queues in Python. They are:
-
- First-in First-out Python Queue
- Python Last-in First-out Queue
- Python Priority Queue
- Circular Queue in Python
1. First-in First-out Python Queue
In the first-in-first-out queue, the first tasks added are the first retrieved. It is just like putting the element inside an open cylinder. Before we move ahead, we need to import one library called a queue. After that, we can create instances that can be viewed as containers.
Let us see how to do that.
This chunk of code will import the queue library and will create one instance of the queue. By default, this queue in python is of type first-in first-out (FIFO type). In the case of the FIFO queue, the item that we enter first gets out first.
1.1. Adding and Removing Elements in a Python Queue
Let’s go through the code step by step to understand how the menu-driven script works:
1. Import the required module:
from collections import deque
Here, we import the `deque` class from the `collections` module. The `deque` class provides an implementation of a double-ended queue, which we will use to create a queue data structure.
2. Create an empty queue:
queue = deque()
We create an empty queue using the `deque()` constructor from the `deque` class. This creates an empty queue object that we will use to store the elements.
3. Start the menu-driven loop:
while True:
print("Menu:")
print("1. Add element to the queue")
print("2. Remove element from the queue")
print("3. Display elements in the queue")
print("4. Exit")
We print the menu options to the console, presenting the available actions to the user.
4. Get the user’s choice:
choice = input("Enter your choice (1-4): ")
We use the `input()` function to prompt the user to enter their choice. The user’s input is stored in the `choice` variable as a string.
5. Perform the corresponding action based on the user’s choice:
if choice == '1':
element = input("Enter an element to add: ")
queue.append(element)
print("Element added to the queue.")
If the user enters `’1’`, we prompt them to enter an element to add to the queue using the `input()` function. The element is then appended to the end of the queue using the `append()` method. We display a message indicating that the element has been added to the queue.
elif choice == '2':
if len(queue) > 0:
removed_element = queue.popleft()
print("Removed element:", removed_element)
else:
print("Queue is empty.")
If the user enters `’2’`, we first check if the queue is not empty (`len(queue) > 0`). If the queue is not empty, we use the `popleft()` method to remove the element at the front of the queue, and we print the removed element. If the queue is empty, we display a message indicating that the queue is empty.
elif choice == '3':
if len(queue) > 0:
print("Elements in the queue:")
for element in queue:
print(element)
else:
print("Queue is empty.")
If the user enters `’3’`, we again check if the queue is not empty (`len(queue) > 0`). If the queue is not empty, we print all the elements in the queue using a `for` loop. If the queue is empty, we display a message indicating that the queue is empty.
elif choice == '4':
print("Exiting...")
break
If the user enters `’4’`, we display a message indicating that the program is exiting, and then we break out of the loop, ending the program.
else:
print("Invalid choice. Please try again.")
If the user enters an invalid choice (other than `’1’`, `’2’`, `’3’`, or `’4’`), we display a message indicating that the choice is invalid, and the loop continues to prompt the user for another choice.
Overall, this script creates a menu-driven interface where the user can add elements to a queue, remove elements from the queue, display the elements in the queue, or exit the program. The script continues to present the menu options to the user until they choose to exit.

2. Python Last-in First-out Queue
In this type of queue, the element that goes in first comes out last. In other words, the one that goes, at last, comes out first. But unlike FIFO (which is considered as the default queue type), we have to add a special function to operate LIFO queues.
Let us explore the LIFO queue with the help of an example:
2.1. Adding and removing items into a queue
queue = [] # Initialize an empty queue
def enqueue(element):
queue.append(element)
print("Element", element, "added to the queue.")
def dequeue():
if len(queue) == 0:
print("The queue is empty.")
else:
element = queue.pop(0)
print("Element", element, "removed from the queue.")
def display_queue():
if len(queue) == 0:
print("The queue is empty.")
else:
print("Elements in the queue:")
for element in queue:
print(element)
# Main program loop
while True:
print("nQUEUE OPERATIONS")
print("1. Add element to the queue")
print("2. Remove element from the queue")
print("3. Display elements in the queue")
print("4. Quit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
element = input("Enter the element to add: ")
enqueue(element)
elif choice == '2':
dequeue()
elif choice == '3':
display_queue()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
In this script, the enqueue() function adds an element to the queue by appending it to the end of the queue list. The dequeue() function removes the first element from the queue using the pop(0) method. The display_queue() function iterates through the elements in the queue list and displays them.
The main program loop allows users to choose between adding an element, removing an element, displaying the elements, or quitting the program. The loop continues until the user chooses to quit.
You can run this script to interact with the queue by adding, removing, and displaying elements based on the user’s input.
3. Python Priority Queue
A priority queue in Python is an abstract data structure that is like a normal queue but where each item has a special “key” to related to its “priority.”
Again, to be able to perform priority queue operations, we have to use another function shown below.
Let us see how this works with the help of an example.
Example:
Let us add 5 elements into a queue using the priority queue function.
Now that we have the items in the queue, let us use the Python for loop to remove the items. We will be using the q.qsize() function (returns the size of the queue) in order to run the for loop function.
As we can see here, the item with the lowest value gets out first. But again, if two elements are of the same value, then the order is taken into consideration while removing the same elements from the Python queue.
This brings us to the end of this module in Python Tutorial. Now, if you want to know why Python is the preferred language for data science, you can go through this blog on Python Data Science tutorial.
3.1. Adding & Removing Items in Queue
Queue is a collection of similar items arranged in a linear order. A simple queue items are can be accessed in the First-in-First-out(FIFO). Let’s understand how to add or remove items from a LIFO queue.
3.1.1. Adding Items to Queue
To add items in a queue, put() function is used. Let’s see an example below:
3.1.2. Removing Items from Queue
To remove an element from the queue, get() function is used. Below is an example of the same:
3.2. Sorting a Queue
Sorting means rearranging the queue items in either ascending or descending order. Below is the program used to sort the queue elements in ascending order:
Alternatively, we can also use deque and sorted() for the same. Check out the below-mentioned code:
3.3. Reversing Queue
Reversing will print the queue elements from right to left. Below is the program to do so:
3.4. Enqueue Function in Python
Enqueue(): In Python, the term “enqueue()” refers to a function that is used to add an element to the end of a queue data structure. A queue follows the first-in, first-out (FIFO) principle, meaning that the element enqueued first will be dequeued first from the front of the queue.
The enqueue() function is responsible for appending or inserting an element at the rear or end of the queue, expanding its size. It ensures that previously enqueued elements remain in their original order.
The enqueue() function typically takes two parameters: the queue data structure and the element to be enqueued. The function modifies the queue by adding the element to the end, without returning any value. The specific implementation of the enqueue() function may vary depending on the choice of data structure used to represent the queue.
Here’s the code example for implementing the enqueue() function in Python using a list as the underlying data structure:
In the above code, the enqueue() function takes two parameters: queue, which represents the queue data structure, and element, which is the item to be enqueued. The function uses the append() method available for lists in Python to add the specified element to the end of the queue list.
The example usage demonstrates how to create an empty queue (my_queue) and enqueue three elements: ‘apple’, ‘banana’, and ‘cherry’. After enqueuing the elements, the print(my_queue) statement outputs [‘apple’, ‘banana’, ‘cherry’], indicating that the elements have been successfully enqueued in the desired order.
4. Circular Queue in Python
In a Python circular queue, the last element is connected to the first element, forming a circle-like structure. It is an extended version of a normal queue.
A circular queue solves one of the major problems of a regular queue. In a regular queue, after some insertion and deletion, there exists empty space which is non-usable.
Here, you can use the indexes 0 and 1 only after you reset the queue by deleting all its elements. This reduces the actual size of the queue.
Implementation of Python Queue
A Python queue is a first-in, first-out (FIFO) data structure that allows you to add and remove items in order. It works similarly to a real-world queue, like the line at a supermarket – the first person to join the queue is the first to be served.
To implement a queue in Python, you can use the queue module. This provides two main classes – Queue and LifoQueue. Queue implements a FIFO queue, while LifoQueue implements a last-in, first-out (LIFO) stack.
For a FIFO queue, the basic operations are:
-
- queue.put(item) – Add an item to the back of the queue
- item = queue.get() – Remove and return an item from the front of the queue
You can also check if the queue is empty with queue.empty() and see how many items are in it with queue.qsize().
Some key advantages of using a queue in Python include effortless first-in, first-out access to items and the ability to process tasks or data in a sequential order. Queues are also useful for implementing things like background task processing.
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
Queues are a fundamental data structure for any Python programmer to be familiar with. Understanding how to take advantage of their first-in, first-out processing capabilities will allow you to build better programs that can effectively handle sequential workloads and operations. If you are interested in learning more about the similar datatypes, then do check out our Python Course!
Our Python Courses Duration and Fees
Cohort Starts on: 20th Apr 2025
₹20,007