A Python list is fast at its end and slow at its front. append and pop() at the end are O(1), but pop(0) moves every remaining item one place left, so it costs O(n). Empty a queue of n items that way and you have written O(n²) code that looks like O(n). collections.deque removes from either end in O(1).
See the difference
from collections import deque
from time import perf_counter
def drain_list(n):
q = list(range(n))
while q:
q.pop(0)
def drain_deque(n):
q = deque(range(n))
while q:
q.popleft()
for n in (25_000, 50_000, 100_000):
times = []
for drain in (drain_list, drain_deque):
start = perf_counter()
drain(n)
times.append((perf_counter() - start) * 1000)
print(f"{n:>7,} items list {times[0]:7.1f} ms deque {times[1]:5.1f} ms")On one laptop with Python 3.13, the list took about 90 ms, 400 ms and 1,900 ms. The deque took 1.5, 3.4 and 6.1 ms. Your numbers will differ, but the shape will not: each time the list doubles, its time more than quadruples, while the deque's time only doubles.
Which to use
- Stack (newest first): a list.
append,pop()andstack[-1]are all O(1) at the end. A deque works too, but a list is simpler and supports slicing. - Queue (oldest first), including BFS: a deque, with
appendandpopleft. - Sliding window of the last k items:
deque(maxlen=k). Appending to a full deque drops the item at the other end. - Random access by index: a list. A deque reads its ends in O(1) but its middle in O(n), and it does not support slicing or
sort. - Passing work between threads:
queue.Queue. It adds locking to every operation, which a single-threaded algorithm does not need.
A BFS with the right queue
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft() # O(1), unlike list.pop(0)
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']Mark a node as seen when you add it to the queue, not when you remove it. Otherwise a node reachable by two paths, like d here, is queued twice.
Both containers raise IndexError when you pop from them empty, so test if queue: first. An empty list and an empty deque are both false.
Chapter 6 of our free Python for DSA book builds stacks and queues this way, and chapter 14 uses the deque for BFS and recovering shortest paths. Books in four more languages are on the DSA hub.