#PYTHON QUEUE CODE#
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. In this article, we have understood the concept behind queue and implemented it in python. Also, the inbuilt functions in Python make the code short and simple. Stack works on the principle of Last-in, first-out. Following are different ways to implement in Python. Unlike C++ STL and Java Collections, Python does have specific classes/interfaces for Stack and Queue. The complete code for implementing a queue in python is follows.Ĭreated on Sun Apr 25 20:15:56 aditya1117 Prerequisites : list and Deque in Python. To get the front element in the queue, we have to return the first element of the list in the queue. Return False Get the front element in the queue 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. Return self.queueLength Check if the queue is empty The length() method implements it as follows. To find the length of the queue, we just have to look at the value of the queueLength variable. Print(str(e)) Find the length of the queue 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. Before dequeue operation, we will check if the queue is empty. Then, we will decrement the queueLength by 1. To implement the dequeue operation, we will just pop the first element of the list in the queue. When we remove an element from a queue, the operation is termed as dequeue operation. The enQueue() method to implement the enqueue operation will take the element as argument and perform the operation. Then, we will increment the queueLength by one. To implement the enqueue operation, we will just append the element to the list in the queue. When we add an element to a queue, the operation is termed as enqueue operation. Self.queueLength=0 Add element to a queue in python The Queue class implementation in python will be as follows. 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. Queue is a linear data structure in which we can only access or remove the element which was added first to it.
In this article, we will study the underlying concept behind queue data structure and implement it in python. The element which was added first can only be accessed or deleted. The queue data structure follows last in first out (LIFO) order for accessing elements. You must have seen queues in real life while waiting for an appointment to doctor or while ordering food in a restaurant.