Queues
Follow a first-in-first-out line and see why a queue needs a front and a back.
queue, fifo, enqueue, dequeue, deque, waiting lineA line at a water fountain
Imagine A joins a line, then B joins behind A. When the fountain is free, A leaves the front first. B keeps waiting.
A queue follows first in, first out, or FIFO: add at the back and remove from the front.
front back
| |
v v
[A] -> [B] -> [C]
next to leave newest arrival
The arrows describe order in the line. They do not require a particular implementation or mean the queue sorts its items.
Why we need it and where it is used
A queue is useful when requests should be handled in arrival order. For example, a small print manager could put print jobs in a line. Another use is keeping track of items waiting to be processed in an algorithm.
FIFO does not promise fairness across every real system: priorities, cancellations, multiple workers, or failures can change the order in which work finishes. Our simple example has one queue and removes one item at a time.
Follow enqueue and dequeue
| Action | Queue from front to back | Result |
|---|---|---|
| Start | empty | No front item |
| Enqueue A | A | A is at the front |
| Enqueue B | A, B | B joins the back |
| Peek | A, B | See A without removing it |
| Dequeue | B | Remove and return A |
Enqueue means add at the back; dequeue means remove from the front. An empty queue has no front item. Compare this with a stack, which removes the most recently added item.
See the reasoning
Follow the example one step at a time
Follow a first-in, first-out queue. This is a prepared teaching demonstration, not live code execution.
Start empty
front [ ] back
There is no front item yet.
Python illustration
from collections import deque
waiting = deque()
waiting.append("A")
waiting.append("B")
print("front:", waiting[0])
print("leave:", waiting.popleft())
print("leave:", waiting.popleft())
print("empty:", len(waiting) == 0)
Prepared output — not live execution:
front: A
leave: A
leave: B
empty: True
We use the left end as the front. waiting[0] reads without removing;
popleft() removes and returns the front. Both raise IndexError if the deque
is empty. Check for an item or handle the exception when needed.
Time, space, and common mistakes
Python's collections.deque supports approximately O(1) appends and pops at
either end. Storing n items uses O(n) space. These bounds describe this
implementation and operations at the ends; they do not mean every operation
on every queue is O(1).
Repeatedly using list.pop(0) for a long queue can cost O(n) per removal,
because later references shift. Also, a deque is not the same as
queue.Queue, which has a different API and is designed for coordinating
threads.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
