Demonstration of Queue data structure with Python code

Vishvajit Bakarola
3 min readJan 24, 2023

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It is an ordered collection of elements, where elements are added to the back of the queue (rear) and removed from the front of the queue (head). The front of the queue is the element that has been in the queue for the longest time, and the rear of the queue is the element that has been added most recently.

A queue can be implemented using an array, a linked list, or a circular buffer. Queues can be classified into several types:

  • Simple Queue: It has a fixed size and once the size is full, no more elements can be added.
  • Circular Queue: It is also a fixed size queue but it uses a circular buffer to store elements. Once the size is full, the oldest element is overwritten.
  • Priority Queue: It is a queue where elements are prioritized. Elements with higher priority are dequeued first.
  • Double Ended Queue (Deque): It is a queue that allows elements to be added and removed from both ends.

Some of the most common operations in a queue are:

  • enqueue: adding an element to the rear of the queue
  • dequeue: removing an element from the front of the queue
  • peek: looking at the element at the front of the queue without removing it
  • size: checking the number of elements in the queue

Queues are useful in a variety of situations, such as implementing task schedulers, managing network packets, simulating real-world queues, and more.

Following is an example of a simple implementation of a queue in Python using a list:

class Queue:
def __init__(self):
self.queue = []

def enqueue(self, item):
self.queue.append(item)

def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)

def size(self):
return len(self.queue)

# create an instance of the queue
my_queue = Queue()

# add some elements to the queue
my_queue.enqueue(1)
my_queue.enqueue(2)
my_queue.enqueue(3)

# remove an element from the queue
print(my_queue.dequeue()) # prints 1

# check the size of the queue
print(my_queue.size()) # prints 2

In the above example, the class Queue has three methods: enqueue, dequeue, and size. The enqueue method is used to add an item to the queue, the dequeue method is used to remove an item from the front of the queue, and the size method returns the number of items in the queue.

In this example, The queue is implemented using a list, where the append method is used to add an item to the rear of the list and the pop method with index 0 is used to remove an item from the front of the list.

Please note that this is a basic example of a queue in Python, and there are many other ways to implement a queue in python, such as using collections module, heapq module and etc.

Happy Reading…

--

--