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
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
- The list
queueholds the items in order: index 0 is the front of the queue and the last element is the rear. enqueue()adds at the rear withappend(), anddequeue()removes from the front withpop(0).- 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.
- Both
dequeue()andfront()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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises