• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Queue / Queue in Python

Queue in Python

Author: Aditya Raj
Last Updated: May 25, 2021

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.

#!/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.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Queue Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us