Code Snippets
/

deque for O(1) Append and Pop on Both Ends

deque for O(1) Append and Pop on Both Ends

A `collections.deque` (double-ended queue) supports O(1) `append`, `appendleft`, `pop`, and `popleft`, while a Python `list` is O(n) for left-side operations. This snippet covers the deque-as-queue pattern that powers BFS, the deque-as-rolling-buffer pattern with `maxlen`, and the rotate trick for cyclic processing.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
queue

920 views

9

from collections import deque

graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D', 'E'], 'D': [], 'E': []}

def bfs(start):
    visited = {start}
    order = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            if nxt in visited:
                continue
            visited.add(nxt)
            queue.append(nxt)
    return order

print(bfs('A'))  # ['A', 'B', 'C', 'D', 'E']

BFS needs a FIFO queue: append to the end, popleft from the front. A Python list supports append in O(1) but pop(0) in O(n) because every other element must shift. deque makes both O(1), which is what makes a BFS on a million-node graph feasible. Always reach for deque when the algorithm needs a real queue; using a list 'because it works' is one of the most common Python performance bugs in graph code.