Implementation of Queue using List in Python
Last Updated :
14 Feb, 2025
A queue is a linear data structure that follows the FIFO (First In First Out) principle. The first element added is the first one to be removed. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In Python, we can implement a queue using both a regular list and a circular list.
Queue1. Queue Implementation Using List
The simplest way to implement a queue is using Python's built-in list. In this implementation, we can perform the following operations:
- Enqueue: Adds new elements to the end of the queue. Checks if the queue has space before insertion, then increments the size.
- Dequeue: Removes the front element by shifting all remaining elements one position to the left. Decrements the queue size after removal.
- getFront: Returns the first element of the queue if it’s not empty. Returns -1 if the queue is empty.
- Display: Iterates through the queue from the front to the current size and prints each element.
Below is the illustration:
Here’s how we can implement the queue using a list:
Python
# Python program to implement
# queue using array.
class Queue:
def __init__(self, q_size):
self.arr = [0] * q_size
self.size = 0
self.capacity = q_size
self.front = 0
# Function to add an element
# to queue.
def enqueue(self, x):
# If queue is full
if self.size == self.capacity:
return
self.arr[self.size] = x
# Increment queue size.
self.size += 1
# Function to pop front
# element from queue.
def dequeue(self):
# If queue is empty
if self.size == 0:
return
# Shift all the elements
# to the left.
for i in range(1, self.size):
self.arr[i-1] = self.arr[i]
# decrement queue size
self.size -= 1
# Function which returns
# the front element.
def getFront(self):
# If queue is empty
if self.size == 0:
return -1
return self.arr[self.front]
# Function which prints
# the elements of array.
def display(self):
for i in range(self.front, self.size):
print(self.arr[i], end=" ")
print()
if __name__ == "__main__":
q = Queue(4)
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.getFront())
q.dequeue()
q.enqueue(4)
q.display()
Time Complexity: O(1) for Enqueue (element insertion in the queue) as we simply increment pointer and put value in array, O(n) for Dequeue (element removing from the queue).
Auxiliary Space: O(n), as here we are using an n size array for implementing Queue
We can notice that the Dequeue operation is O(n) which is not acceptable. The enqueue and dequeue both operations should have O(1) time complexity. That is why if we wish to implement a queue using array (because of array advantages like cache friendliness and random access), we do circular list implementation of queue.
2. Queue Implementation Using Circular List
A circular queue is an optimized version of a queue that solves the problem of unused space in a list-based queue when elements are dequeued. In a circular queue, the last position is connected to the first, and both front and rear pointers wrap around when they reach the end of the list.
- Initialize an array of size n, where n is the maximum number of elements that the queue can hold.
- Initialize three variables (size, capacity, and front.)
- Enqueue: To enqueue an element x into the queue, do the following:
- Check if size == capacity (queue is full), display “Queue is full”.
- If not full: calculate rear = (front + size) % capacity and Insert value at the rear index. Increment size by 1.
- Dequeue: To dequeue an element from the queue, do the following:
- Check if size == 0 (queue is empty), display “Queue is empty”.
- If not empty: retrieve the element at the front index and move front = (front + 1) % capacity. Also, decrement size by 1 and return the removed element.
Illustration of Circular Queue:
Below is the implementation of above approach:
Python
# python3 program for insertion and
# deletion in Circular Queue
class MyQueue:
def __init__(self, c):
self.l = [None] * c
self.cap = c
self.size = 0
self.front = 0
def getFront(self):
# Check if queue is empty
if self.size == 0:
return None
return self.l[self.front]
def getRear(self):
# Check if queue is empty
if self.size == 0:
return None
# Calculate rear index
rear = (self.front + self.size - 1) % self.cap
return self.l[rear]
def enqueue(self, x):
# Check if queue is full
if self.size == self.cap:
return
# Calculate rear index
rear = (self.front + self.size) % self.cap
self.l[rear] = x
self.size += 1
def dequeue(self):
# Check if queue is empty
if self.size == 0:
return None
res = self.l[self.front]
# Move front index circularly
self.front = (self.front + 1) % self.cap
self.size -= 1
return res
q = MyQueue(4)
q.enqueue(10)
print(q.getFront(), q.getRear())
q.enqueue(20)
print(q.getFront(), q.getRear())
q.enqueue(30)
print(q.getFront(), q.getRear())
q.enqueue(40)
print(q.getFront(), q.getRear())
q.dequeue()
print(q.getFront(), q.getRear())
q.dequeue()
print(q.getFront(), q.getRear())
q.enqueue(50)
print(q.getFront(), q.getRear())
Output10 10
10 20
10 30
10 40
20 40
30 40
30 50
Complexity Analysis of Circular Queue Operations
Time Complexity:
Operation | Time Complexity |
---|
enqueue(x) | O(1) |
---|
dequeue() | O(1) |
---|
getFront() | O(1) |
---|
getRear() | O(1) |
---|
Auxiliary Space: O(size), where size is the number of elements in the circular queue.
Similar Reads
Implementation of Queue using Linked List in Python
A queue is a linear data structure that follows the FIFO (First In First Out) principle. The first element added is the first one to be removed. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that ca
4 min read
Python | Implementation of Queues in Multi-Threading
Prerequisites: Before reading this article, some important background reading is recommended to ensure that one is well equipped with the basic knowledge of threads as well as the basic knowledge of queues before trying to mix the two together. The official documentation is especially important. Top
7 min read
Queue - Linked List Implementation
In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty. Approach: To solve the problem follow the below idea: we maintain two pointers, front and rear. The front points to the first item of the queue and rear points
8 min read
Implementation of Queue in Javascript
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front. Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Re
7 min read
Python | Queue using Doubly Linked List
A Queue is a collection of objects that are inserted and removed using First in First out Principle(FIFO). Insertion is done at the back(Rear) of the Queue and elements are accessed and deleted from first(Front) location in the queue. Queue Operations:1. enqueue() : Adds element to the back of Queue
3 min read
Indexed Priority Queue with Implementation
Priority queue is a data structure in which data is stored on basis of its priority. In an Indexed Priority Queue, data is stored just like standard priority queue and along with this, the value of a data can be updated using its key. It is called "indexed" because a hash map can be used to store th
8 min read
Implementation of Deque using doubly linked list
A Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we
9 min read
Dumping queue into list or array in Python
Prerequisite: Queue in Python Here given a queue and our task is to dump the queue into list or array. We are to see two methods to achieve the objective of our solution. Example 1: In this example, we will create a queue using the collection package and then cast it into the list C/C++ Code # Pytho
2 min read
Deque Implementation in Python
A deque (double-ended queue) is a data structure that allows insertion and deletion from both the front and rear in O(1) time in optimized implementations. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In
6 min read
Array implementation of queue (Simple)
Please note that a simple array implementation discussed here is not used in practice as it is not efficient. In practice, we either use Linked List Implementation of Queue or circular array implementation of queue. The idea of this post is to give you a background as to why we need a circular array
5 min read