You must have seen queues in real life while waiting for an appointment to doctor or while ordering food in a restaurant. The queue data structure follows last in first out (LIFO) order for accessing elements. The element which was added first can only be accessed or deleted. In this article, we will study the underlying concept behind queue data structure and implement it in python.

How to implement queue in python?

Queue is a linear data structure in which we can only access or remove the element which was added first to it. We will implement a queue using a list. For implementation, we will define a queue class which will have a list to contain the elements and a queueLength field to contain the length of the list. The Queue class implementation in python will be as follows.

class Queue:
    def __init__(self):
        self.queueList=list()
        self.queueLength=0

Add element to a queue in python

When we add an element to a queue, the operation is termed as enqueue operation. To implement the enqueue operation, we will just append the element to the list in the queue. Then, we will increment the queueLength by one. The enQueue() method to implement the enqueue operation will take the element as argument and perform the operation. This can be implemented as follows.

def enQueue(self,data):
        self.queueList.append(data)
        self.queueLength=self.queueLength+1

Remove element from queue in python

When we remove an element from a queue, the operation is termed as dequeue operation. To implement the dequeue operation, we will just pop the first element of the list in the queue. Then, we will decrement the queueLength by 1. Before dequeue operation, we will check if the queue is empty. If yes, an exception will be raised using python try except with a message that the queue is empty.Otherwise dequeue operation will be done.The deQueue() method to implement the dequeue operation can be implemented as follows.

def deQueue(self):
        try:
            if self.queueLength==0:
                raise Exception("Queue is Empty")
            else:
                temp=self.queueList.pop(0)
                self.queueLength=self.queueLength-1
                return temp
        except Exception as e:
            print(str(e))

Find the length of the queue

To find the length of the queue, we just have to look at the value of the queueLength variable. The length() method implements it as follows.

def length(self):
        return self.queueLength

Check if the queue is empty

To check if the queue is empty, we have to find if the queueLength is 0.The isEmpty() method will implement the logic as follows.

def isEmpty(self):
        if self.queueLength==0:
            return True
        else:
            return False

Get the front element in the queue

To get the front element in the queue, we have to return the first element of the list in the queue. This can be implemented as follows.

def front(self):
        try:
            if self.queueLength==0:
                raise Exception("Queue is Empty")
            else:
                temp=self.queueList[-1]
                return temp
        except Exception as e:
            print(str(e))

The complete code for implementing a queue in python is follows.

Get the front element in the queue

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 20:15:56 2021

@author: aditya1117
"""

class Queue:
    def __init__(self):
        self.queueList=list()
        self.queueLength=0
    def enQueue(self,data):
        self.queueList.append(data)
        self.queueLength=self.queueLength+1
    def deQueue(self):
        try:
            if self.queueLength==0:
                raise Exception("Queue is Empty")
            else:
                temp=self.queueList.pop(0)
                self.queueLength=self.queueLength-1
                return temp
        except Exception as e:
            print(str(e))
    def isEmpty(self):
        if self.queueLength==0:
            return True
        else:
            return False
    def length(self):
        return self.queueLength
    def front(self):
        try:
            if self.queueLength==0:
                raise Exception("Queue is Empty")
            else:
                temp=self.queueList[-1]
                return temp
        except Exception as e:
            print(str(e))

Conclusion

In this article, we have understood the concept behind queue and implemented it in python. Copy the complete code given above, paste it in your IDE to experiment  with the operations to understand the concepts and see how a queue is different from other data structures like python dictionary, list and sets. Stay tuned for more informative articles.

Leave a Reply

Your email address will not be published. Required fields are marked *