A queue is a first-in-first-out (FIFO) structure — the first item added is the first one removed, like a line at a checkout counter. Queues come up in task scheduling, breadth-first search, and request processing. You could build one with a plain Python list, but there's a performance trap worth knowing about before you do.
A list's pop(0) (removing from the front) is O(n), because every remaining element has to shift left by one. For a queue that's being used heavily, that adds up fast. collections.deque ("double-ended queue") solves this — it's implemented so that adding or removing from either end is O(1).
Program to Implement a Queue Using collections.deque
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def enqueue(self, item):
self.items.append(item) # add to the back
def dequeue(self):
if self.is_empty():
raise IndexError("dequeue from an empty queue")
return self.items.popleft() # remove from the front
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Demo
queue = Queue()
queue.enqueue("Alice")
queue.enqueue("Bob")
queue.enqueue("Charlie")
print(f"Queue size: {queue.size()}")
print(f"Serving: {queue.dequeue()}")
print(f"Serving: {queue.dequeue()}")
print(f"Queue size: {queue.size()}")
Output:
Queue size: 3
Serving: Alice
Serving: Bob
Queue size: 1
"Alice" was enqueued first and is also the first one served — that's the FIFO behavior a queue guarantees. The whole implementation is really just a thin wrapper: append() adds to the right side of the deque, and popleft() removes from the left, so the oldest item is always the next one out.
You rarely need to write this class yourself in real projects — deque is already queue-ready out of the box (d.append(x) / d.popleft()), and the standard library also ships queue.Queue for thread-safe producer/consumer scenarios. But implementing it manually, the same way you might implement a stack using a list, is a common interview exercise because it tests whether you understand *why* the underlying data structure matters, not just that the operations exist.
