Sub topic 2
Queues: Why First-In, First-Out Matters
Breadth-first search depends on one data structure: the queue. When you swap the queue for a different container, the same loop visits vertices in a different order and stops finding shortest paths. This chapter explains what a FIFO queue guarantees and how to get one with efficient operations in Python. It also covers the common mistakes that make a BFS slow or incorrect.
This chapter assumes you can read basic Python, know lists, dictionaries, and sets, and understand Big-O notation. It uses the adjacency-list graphs from the previous chapter.
What FIFO Means
A queue is a container with two main operations:
- Enqueue adds an item at the back.
- Dequeue removes the item at the front.
This rule is called first-in, first-out (FIFO). The item that has waited longest always comes out next. A checkout line at a shop works the same way.
A stack is the opposite. It is last-in, first-out (LIFO): you push and pop at the same end, so the newest item comes out first. Both containers hold the same items. The only difference is which item leaves next, and for graph traversal that difference decides the whole visiting order.
Why BFS Needs FIFO Order
BFS finds vertices in order of distance. It processes one vertex and enqueues that vertex's undiscovered neighbors, which sit one edge farther from the source. FIFO order means every vertex discovered earlier is processed before any vertex discovered later. So all vertices at distance 1 come out before any vertex at distance 2, and so on.
Here is a trace on the graph used throughout this tutorial. The distance of each vertex from A is in parentheses.
| Step | Dequeued | Newly enqueued | Queue afterward (front to back) |
|---|---|---|---|
| 0 | none | A (0) | A |
| 1 | A | B (1), C (1) | B, C |
| 2 | B | D (2) | C, D |
| 3 | C | E (2) | D, E |
| 4 | D | F (3) | E, F |
| 5 | E | none (F already seen) | F |
| 6 | F | none | empty |
Look at the distances in the last column. At every step the queue holds vertices from at most two consecutive distances, d and d + 1, and all the d vertices sit in front of all the d + 1 vertices. This invariant is why BFS works. A later chapter proves it formally and uses it to compute shortest paths.
Watching a Stack Break the Order
The clearest way to see what FIFO contributes is to run the same loop twice, once taking from the front and once taking from the back. Everything else stays the same, including marking vertices when they are added.
from collections import deque
def traverse(graph, start, use_queue):
visited = {start}
order = []
container = deque([start])
while container:
node = container.popleft() if use_queue else container.pop()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
container.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(traverse(graph, 'A', use_queue=True)) # ['A', 'B', 'C', 'D', 'E', 'F']
print(traverse(graph, 'A', use_queue=False)) # ['A', 'C', 'E', 'F', 'D', 'B']The stack version reaches F (distance 3) before B (distance 1). It dives down the most recently found branch, which is depth-first behavior. A real depth-first search is usually written differently, and the final chapter compares the two properly. For now the point is narrow: when you change only the removal end, you lose the layer-by-layer order.
Choosing a Queue in Python
Python has several containers that can act as a queue. Only one of them fits BFS well.
| Container | Enqueue | Dequeue | Fit for BFS |
|---|---|---|---|
| `list` with `append` / `pop(0)` | O(1) amortized | O(n): shifts every remaining item | Correct but slow on large graphs |
| `collections.deque` with `append` / `popleft` | O(1) | O(1) | The standard choice |
| `queue.Queue` with `put` / `get` | O(1) plus locking | O(1) plus locking | Built for threads; extra overhead, and `get` blocks when empty |
| `heapq` on a list | O(log n) | O(log n) | A priority queue, not FIFO; used by Dijkstra's algorithm |
Why `list.pop(0)` is slow
A Python list stores its items in one contiguous array. Removing index 0 forces every other item to move down one slot, so the cost grows with the length of the list. Over a full BFS, the queue can hold a large share of the vertices at once, and the total work can grow toward O(V²) instead of O(V + E).
A deque (double-ended queue) stores items in linked blocks of fixed size and keeps pointers to both ends. Adding or removing at either end touches only one block, so it takes constant time.
You can measure the difference yourself. Exact times depend on your machine, but the list times should roughly quadruple each time n doubles, while the deque times roughly double.
import timeit
from collections import deque
def drain_list(n):
items = list(range(n))
while items:
items.pop(0)
def drain_deque(n):
items = deque(range(n))
while items:
items.popleft()
for n in (20_000, 40_000, 80_000):
t_list = timeit.timeit(lambda: drain_list(n), number=3)
t_deque = timeit.timeit(lambda: drain_deque(n), number=3)
print(f"n={n:>6} list.pop(0): {t_list:.3f}s deque.popleft(): {t_deque:.3f}s")The deque operations you need
BFS uses only a few deque operations:
from collections import deque
queue = deque(['A']) # start with the source vertex
queue.append('B') # enqueue at the back
queue.append('C')
print(queue) # deque(['A', 'B', 'C'])
front = queue.popleft() # dequeue from the front
print(front) # A
print(len(queue)) # 2
print(bool(queue)) # True: a non-empty deque is truthy
queue.popleft()
queue.popleft()
print(bool(queue)) # False: the loop `while queue:` stops hereA deque also supports appendleft and pop, the operations for the other end. Plain BFS does not need them. The 0-1 BFS chapter uses appendleft on purpose to put zero-cost neighbors at the front.
Common Errors
Most of these errors produce code that runs without complaint, so they are worth checking for when you write or review a BFS.
- Using
list.pop(0). It gives correct results with quadratic slowdown. On a graph with a few hundred thousand vertices this can change the runtime from under a second to minutes. - Using
pop()on a deque. It turns the queue into a stack and breaks the distance order, as shown above. - Building the deque from a string.
deque('AB')createsdeque(['A', 'B']), two separate vertices. To start with a single vertex named'AB', writedeque(['AB']). - Setting
maxlen.deque(maxlen=k)silently drops items from the opposite end when it is full. In BFS that loses vertices without raising an error. - Indexing into the middle.
queue[i]costs O(n) on a deque for indexes far from either end. BFS never needs it, so if your code uses it, the design probably needs another look. - Calling
get()on an emptyqueue.Queue. It blocks forever by default. If you have a reason to usequeue.Queue, checkempty()before callingget(), or pass a timeout. For single-threaded BFS, usedeque. - Confusing FIFO with priority.
heapqreturns the smallest item, not the oldest one. It is the right tool for weighted shortest paths and the wrong tool for plain BFS.
Edge Cases Worth Knowing
- Empty start. If the source has no neighbors, the queue holds one vertex, the loop runs once, and the result is
[start]. You do not need a special case. - Self-loops and repeated edges. The queue does not stop the same vertex from being added twice. The visited set does that, which is the subject of the next chapter. Without it, a vertex can enter the queue many times, and in a graph with cycles the loop may never end.
- Peak queue size. The queue can hold close to V vertices at once. In a star graph, for example, the center's neighbors all wait together. Plan memory for O(V), not for the depth of the graph.
- Mutation while iterating. Never loop over the queue with
for x in queue:while appending to it. Python raisesRuntimeError: deque mutated during iteration. Usewhile queue:withpopleft().
Exercise
Replace deque with a plain list in the traverse function, using container.pop(0) for the queue case. Does the visiting order change? What changes as the graph grows?
Show answer
The order stays exactly the same, ['A', 'B', 'C', 'D', 'E', 'F'], because pop(0) still removes the oldest item. The running time changes: each pop(0) shifts every remaining element, so dequeuing costs O(n) instead of O(1). The total work can grow quadratically in the number of vertices instead of staying O(V + E).
Exercise
In a BFS from source S, the queue currently holds vertices at distances [3, 3, 4, 4, 4] from front to back. Could the next state be [3, 4, 4, 4, 5]? Could it be [3, 4, 4, 4, 4]? Explain using the FIFO invariant.
Show answer
[3, 4, 4, 4, 5] is impossible. The vertex removed has distance 3, so any newly enqueued neighbor has distance 4, never 5. [3, 4, 4, 4, 4] is possible: removing the front distance-3 vertex and enqueuing one undiscovered distance-4 neighbor gives exactly that. The queue always holds at most two consecutive distances, with the smaller ones in front.
Exercise
A colleague writes queue = deque(maxlen=1000) "to cap memory" in a BFS over a large graph. What goes wrong, and what is a correct way to limit work?
Show answer
When the deque is full, each append silently discards the item at the front, so vertices that were already marked as visited are dropped before they are processed. Parts of the graph go unexplored with no error raised. To limit work, stop the search explicitly, for example by breaking when a distance threshold or a processed-vertex count is reached, and leave the queue unbounded.