Build the mental model
A queue applies the opposite convention from a stack: elements come out in exactly the order they arrived — First In, First Out (FIFO) — like a line of customers at a checkout counter. Implementing a queue with a plain Python list runs into trouble: append() adds to the end in O(1), but pop(0), which removes from the front, has to shift every remaining element left by one, making it O(n). That's badly inefficient for a queue. collections.deque has no such limitation — built on a doubly linked structure, both append() and popleft() are O(1), so deque is the correct standard-library choice for implementing a queue in Python. The classic use cases are task scheduling, where jobs need to be processed in the order they arrived, and breadth-first traversal, where nodes get enqueued in the order they're discovered so a graph or tree is explored level by level — laying the groundwork for the later BFS lesson.
Connect it to a real scenario
The Tutorial Platform's background job system runs on a queue — each time a lesson is published, jobs like 'rebuild search index' and 'send notification' are enqueued, and a worker process dequeues and processes them in FIFO order.
Try the working example
from collections import deque
task_queue = deque()
# enqueue: add new tasks to the back - O(1)
task_queue.append("index new lesson")
task_queue.append("rebuild search index")
task_queue.append("send notification")
# dequeue: process tasks from the front, in arrival order - O(1)
while task_queue:
task = task_queue.popleft()
print("processing:", task)
# A plain list would need task_queue.pop(0), which is O(n) because
# every remaining element has to shift left one slot each time.Prints "processing: index new lesson", "processing: rebuild search index", "processing: send notification" in that exact order, matching FIFO arrival order.5-minute try-it
Try inserting a priority job (e.g. "urgent fix") at the very front of the queue — which deque method lets you do this — and print the resulting processing order.
One important caution
Implementing a queue with a plain list and pop(0) — as the task count grows, the shifting cost makes the queue progressively slower
Using append()/pop() on both ends like a stack instead of append()/popleft() — this silently turns FIFO order into LIFO order, breaking arrival-order processing
Wikipedia — Queue (abstract data type) — Data Structures & Algorithms