A queue handles the oldest waiting item first. That simple rule makes it useful for fair scheduling and breadth-first exploration.
A deque gives both ends a door
Deque means double-ended queue. It can add or remove efficiently at both the front and back, so it can behave like a queue or a stack.
- append adds at the back.
- popleft serves the front.
- appendleft adds at the front.
- pop removes from the back.
Do not use a slow front removal
Removing index zero from a Python list shifts the remaining items. collections.deque is designed for efficient operations at both ends.
from collections import deque
def serve(tasks):
waiting = deque(tasks)
while waiting:
task = waiting.popleft()
print("Serving", task)
serve(["upload", "email", "backup"])Queues appear in message systems, printer jobs, customer lines, and BFS. The important clue is arrival order.
Your tiny challenge
Start with A, B, C in a deque. Remove from the front, add D at the back, then add X at the front. What remains?
