Skip to content

Module 18 · Algorithms and Problem Solving — topic 15 of 18

Queues

The first-in, first-out (FIFO) data structure: queues with collections.deque, simulations, breadth-first search, round-robin scheduling, and priority queues with heapq.

Beginner 10 min read·Lesson 275 of 306 in Python Programming

Learning objectives

  • Use collections.deque as a queue
  • Simulate queues of tasks
  • Apply queues to breadth-first search and priority scheduling

Definition

A queue is a collection where items are added at the back and removed from the front, so the first item added is the first removed: first in, first out (FIFO).

Introduction

People waiting at a ticket counter, documents waiting for a printer and messages waiting to be processed all form queues.

Why it matters

Queues model fairness and order. They are essential for scheduling, simulations, network buffers and searching graphs level by level.

Detailed explanation

enqueue adds an item to the back; dequeue removes the item at the front.

collections.deque supports append and popleft in O(1). Lists are a poor choice because pop(0) is O(n).

Check for an empty queue with if queue: before dequeuing, or handle IndexError.

Simulations process events in arrival order: a printer queue, a bank counter, a call centre.

Breadth-first search (BFS) explores a graph level by level using a queue, and finds the shortest path (fewest steps) in an unweighted graph.

A priority queue always removes the most important item first. heapq implements one with a list: heappush adds, heappop removes the smallest (highest-priority) item in O(log n).

queue.Queue is a thread-safe queue for passing work between threads.

deque(maxlen=n) keeps only the most recent n items, useful for recent-history buffers.

Syntax

Python
from collections import deque
import heapq
q = deque()
q.append("job1") # enqueue
first = q.popleft() # dequeue
pq = []
heapq.heappush(pq, (1, "urgent"))
priority, task = heapq.heappop(pq)
  • FIFO: first in, first out.
  • Use deque, not list.pop(0).
  • heapq for priority queues.

Code examples

A FIFO queue

Python
from collections import deque
q = deque()
q.append("Asha")
q.append("Ravi")
q.append("Meera")
print(q.popleft(), q.popleft(), list(q))
Output
Asha Ravi ['Meera']

A printer queue

Python
from collections import deque
jobs = deque([("report.pdf", 3), ("photo.png", 1), ("notes.txt", 2)])
time = 0
while jobs:
name, pages = jobs.popleft()
time += pages
print(f"t={time}: printed {name}")
Output
t=3: printed report.pdf
t=4: printed photo.png
t=6: printed notes.txt

More examples

Shortest path and priorities

Python
import heapq
from collections import deque
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
def bfs_path(start, goal):
queue = deque([[start]])
seen = {start}
while queue:
path = queue.popleft()
if path[-1] == goal:
return path
for nxt in graph[path[-1]]:
if nxt not in seen:
seen.add(nxt)
queue.append(path + [nxt])
return None
print(bfs_path("A", "F"))
tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix bug"))
heapq.heappush(tasks, (3, "reply emails"))
print([heapq.heappop(tasks)[1] for _ in range(3)])
Output
['A', 'B', 'D', 'F']
['fix bug', 'write report', 'reply emails']

Step-by-step explanation

  • BFS keeps whole paths in the queue and expands the shortest ones first.
  • The seen set prevents visiting a node twice, so the first path that reaches F has the fewest steps.
  • heapq always pops the task with the smallest priority number, regardless of insertion order.

Expected output

Running “Shortest path and priorities” prints exactly:

TextOutput
['A', 'B', 'D', 'F']
['fix bug', 'write report', 'reply emails']

Practical applications

  • Task queues in web servers and message brokers.
  • Shortest routes in maps and social-network 'degrees of separation'.

Best practices

  • Use deque for FIFO queues.
  • Use heapq for priorities.
  • Track visited nodes in BFS.

Common mistakes

Using a list as a queue

Avoid

queue = []
queue.pop(0)

Prefer

from collections import deque
queue = deque()
queue.popleft()

list.pop(0) shifts every remaining element, which is slow for long queues.

Important notes

  • Dijkstra's shortest-path algorithm combines BFS ideas with a priority queue for weighted graphs.

Key takeaways

  • Queues are FIFO.
  • deque gives O(1) append and popleft.
  • BFS uses a queue; heapq gives priority queues.

Try it yourself

  1. 1
    Simulate a ticket counter where customers arrive with service times and print waiting times.
  2. 2
    Use BFS to find the shortest path in a small grid maze.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
Practise this topic