• Articles
  • Tutorials
  • Interview Questions

Queue in Python - Implementation Explained

Tutorial Playlist

What is Queue in Python?

Python queue is an important concept in the data structure. Queue in Python is nothing but data item containers. With the help of a queue in Python, we can control the flow of our tasks.

Say, we are manipulating data that is collected from a website and then writing the manipulated data into a .txt file. Now, if we have not collected the data from the website, we would not be able to start the data manipulating task, right? We don’t want to save the data right after collecting it from the website to avoid messing up the workflow of the whole task. Python queue is a great way to keep things on track.

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

So, let’s get started.

Get 100% Hike!

Master Most in Demand Skills Now !

First-in First-out Python Queue

As the name suggests, in the first-in-first-out queue policy, the first element that goes in comes out first. 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.

import queue
q = queue.Queue()

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.

Learn more about Python from an expert. Enroll in our Python training in Bangalore

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.

  1. 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.

  1. Start the menu-driven loop:

while True:

We use an infinite `while` loop, which means the loop will keep running until we explicitly break out of it.

  1. Display the menu:

    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.

  1. 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.

  1. 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.

Learn more about Python Programming from an expert. Enroll in our Python training in Delhi

Become a Full Stack Web Developer

Python Last-in First-out Queue

Again, as the name says, 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:

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.

Certification in Full Stack Web Development

Python Priority Queue

The priority queue in Python is a bit interesting. Here, the order in which we put the items doesn’t matter. What really matters is the value of the items. But how is that going to work? Well, the logic behind this policy is that the lowest-valued item gets out first.

Again, to be able to perform priority queue operations, we have to use another function shown below.

import queue
q= queue.PriorityQueue()

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.

import queue
q= queue.PriorityQueue()
q.put(2)
q.put(4)
q.put(1)
q.put(0)
q.put(2)

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.

import queue
q= queue.PriorityQueue()
q.put(2)
q.put(4)
q.put(1)
q.put(0)
q.put(2)

for i in range(q.qsize()):
print(q.get(i))

output:
1
2
2
4

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.

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. 

Adding Items to Queue

To add items in a queue,  put() function is used. Let’s see an example below:

import queue
#importing the class queue to create an object q
q=queue.Queue(maxsize=5)
#Put() func. is used to insert values
#values are inserted at the end of queue
q.put(5)
q.put(10)
q.put(15)
q.put(20)
q.put(25)

Removing Items from Queue

To remove an element from the queue, get() function is used. Below is an example of the same:

#get() func. will get the values
#the values are fetched from the queue head

for i in range(0,5):
    print(q.get(), end="  ")
Learn more about Python Language from an expert. Enroll in our Python training in Pune

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:

import queue
q=queue.Queue()

q.put(10)
q.put(5)
q.put(15)
q.put(22)
q.put(20)
q.put(25)

size=q.qsize()

for i in range(size):
    x=q.get()
    for j in range(size-1):
        y=q.get()
        if(x>y):
            q.put(y)
        else:
            q.put(x)
            x=y

    q.put(x)

while(q.empty()==False):
    print(q.queue[0],end=" ")
    q.get()

The output of the above program will be:

5 10 15 20 22 25

Alternatively, we can also use deque and sorted() for the same. Check out the below-mentioned code:

def sorting(queue):
    sorted_queue = []
    copied_queue = list(queue)  # Create a copy of the original queue
    while len(copied_queue) > 0:
        min_element = min(copied_queue)  # Find the minimum element in the copied queue
        sorted_queue.append(min_element)  # Enqueue the minimum element to the sorted_queue
        copied_queue.remove(min_element)  # Dequeue the minimum element from the copied queue
    return sorted_queue
# Example usage
my_queue = [10,15,5,22,25,20]  # Creating an unsorted queue
sorted_queue = sorting(my_queue)  # Sorting the queue
print(“Original queue:”, my_queue)
print(“Sorted queue:”, sorted_queue)

Output:
Original queue: [10, 15, 5, 22, 25, 20]
Sorted queue: [5, 10, 15, 20, 22, 25]

Reversing Queue

Reversing will print the queue elements from right to left. Below is the program to do so:

import queue
q=queue.Queue()

q.put(10)
q.put(5)
q.put(15)
q.put(22)
q.put(20)
q.put(25)

def reversequeue(q1,st):
    buff=q1.get()
    if(q1.empty()==False):
        reversequeue(q1,st)
    st.put(buff)
    return st


st=queue.Queue()
qrev=reversequeue(q,st)

size=qrev.qsize()

for i in range(size):
    print(qrev.get(),end=" ")

The output of the above program will be:

25 20 22 15 5 10

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:

def enqueue(queue, element):
queue.append(element)
# Example usage
my_queue = [] # Creating an empty queue
enqueue(my_queue, 'apple') # Enqueueing 'apple'
enqueue(my_queue, 'banana') # Enqueueing 'banana'
enqueue(my_queue, 'cherry') # Enqueueing 'cherry'
print(my_queue) # Output: ['apple', 'banana', 'cherry']

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.

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.

class CircularQueue:
  def __init__(self, maxSize):
    self.queue = list()
    self.maxSize = maxSize
    self.head = 0
    self.tail = 0
  def enqueue(self, data):
    if self.size() == (self.maxSize - 1):
      return("Queue is full!")
    else:
      self.queue.append(data)
      self.tail = (self.tail+1) % self.maxSize
      return True
  def dequeue(self):
    if self.size() == 0:
      return("Queue is empty!")
    else:
      data = self.queue[self.head]
      self.head = (self.head+1) % self.maxSize
      return data
  def size(self):
    if self.tail >= self.head:
      qSize = self.tail - self.head
    else:
      qSize = self.maxSize - (self.head - self.tail)
    return qSize

size = input("Enter the size of the Circular Queue")
q = CircularQueue(int(size))

print(q.enqueue(10))
print(q.enqueue(20))
print(q.enqueue(30))
print(q.enqueue(70))
print(q.enqueue(80))
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

The output will be:

Enter the size of the Circular Queue 4
4
True
True
True
Queue is full!
Queue is full!
10
20
30

Queue is empty!

Further, check out our Python interview questions and answers by experts. Big companies like Netflix and IBM use Python. Dropbox is created in Python, and hundreds of other big companies are also adapting Python. So, this is not a surprise that Python has become one of the fastest-growing programming languages, according to Stack Overflow. The ever-expanding applications of large-scale Data Science and Artificial Intelligence have become two of the most aspiring fields in the 21st century. To be a part of these competitive and lucrative fields, one must fulfill the requirement of having a well-rounded understanding of Python.

For any doubts related to python queue or python tutorial, head to our Python Community right away!

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.

Conclusion

Python queues provide a simple yet powerful way to organize the sequential processing of items or tasks. Whether you need FIFO behavior like a normal queue or LIFO stack-like functionality, the queue module makes it easy to implement both. Using queues allows you to efficiently manage workloads by ensuring items are addressed in the order they are added. This can be quite useful for tasks like background processing, where maintaining order is important. 

Overall, 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.

 

 

Course Schedule

Name Date Details
Python Course 20 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details