Editor

Python Program to Implement a Queue

Intermediate · Data structures

A queue is a data structure where the first item added is the first one removed (FIFO, first in first out), like people waiting in line at a ticket counter. Adding at the rear is called enqueue and removing from the front is called dequeue. This program builds a queue on a Python list and reports underflow when you try to remove from an empty queue.

Program

queue_using_list.py
queue = []
def enqueue(item):
queue.append(item) # join at the rear
print("Joined:", item, "| queue:", queue)
def dequeue():
if len(queue) == 0:
print("Underflow: the queue is empty")
else:
item = queue.pop(0) # leave from the front
print("Served:", item, "| queue:", queue)
def front():
if len(queue) == 0:
print("The queue is empty, no one is at the front")
else:
print("At the front:", queue[0])
enqueue("Asha")
enqueue("Ben")
enqueue("Chitra")
front()
dequeue()
dequeue()
front()
dequeue()
dequeue() # nobody is left, so this is an underflow
Output
Joined: Asha | queue: ['Asha']
Joined: Ben | queue: ['Asha', 'Ben']
Joined: Chitra | queue: ['Asha', 'Ben', 'Chitra']
At the front: Asha
Served: Asha | queue: ['Ben', 'Chitra']
Served: Ben | queue: ['Chitra']
At the front: Chitra
Served: Chitra | queue: []
Underflow: the queue is empty

How it works

  1. The list queue holds the items in order: index 0 is the front of the queue and the last element is the rear.
  2. enqueue() adds at the rear with append(), and dequeue() removes from the front with pop(0).
  3. Asha joined first, so she is served first; that is the difference from a stack, where the last item in is the first one out.
  4. Both dequeue() and front() check for an empty queue first, so the last call prints an underflow message instead of crashing.

Another way to write it

Using collections.deque

Using collections.deque
from collections import deque
queue = deque()
queue.append("Asha")
queue.append("Ben")
queue.append("Chitra")
print("Queue:", list(queue))
while queue: # an empty deque counts as False
print("Served:", queue.popleft())
print("The queue is empty")
Output
Queue: ['Asha', 'Ben', 'Chitra']
Served: Asha
Served: Ben
Served: Chitra
The queue is empty

pop(0) on a list has to shift every other item one place to the left, which gets slow for long queues. A deque removes from the front at once with popleft(), so it is what real programs use.

Try it yourself

Add a size() function that prints how many people are waiting, and call it after each dequeue.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises