This article covers queue implementation in Python. A queue is a linear data structure that follows the FIFO (First–In, First–Out) order, i.e., the item inserted first will be the first one out.

A queue supports the following standard operations:

  1. enqueue: Inserts an element at the rear (right side) of the queue.
  2. dequeue: Removes the element from the front (left side) of the queue and returns it.
  3. peek: Returns the element at the front of the queue without removing it.
  4. isEmpty: Checks whether the queue is empty.
  5. size: Returns the total number of elements present in the queue.

The time complexity of all the above operations should be constant.

Practice this problem

Queue Implementation using a List:

The queue can easily be implemented as a list. Following is the custom queue implementation in Python, which uses a list:

Download  Run Code


Output:
 
Inserting 1
Inserting 2
Inserting 3
The front element is 1
Removing 1
The front element is 2
The queue size is 2
Removing 2
Removing 3
The queue is empty

Using deque():

Python’s library offers a deque object, which stands for the double-ended queue. A deque is a generalization of stack and queues which support constant-time insertions and removals from either side of the deque in either direction.

Following is a simple example demonstrating the usage of deque to implement queue data structure in Python:

Download  Run Code


Output:
 
The front element is 1
The front element is 3
The queue size is 2
The queue is not empty

 
Also See:

Circular Queue implementation in C

Queue Implementation in C++

Queue Implementation in Java

Queue Implementation using a Linked List – C, Java, and Python