`collections.deque`
collections.deque is a double-ended queue: a sequence you can append and pop from either end in O(1) time. It is the right structure for queues, sliding windows, and BFS.
Detailed Explanation
A list is fast at the right end and slow at the left. list.pop(0) and list.insert(0, x) shift every element. A deque is implemented as a doubly linked block of blocks. append, appendleft, pop, and popleft are all O(1). Indexing in the middle is O(n). Random writes are not the point.
Create one with deque(iterable) or deque(). maxlen=n makes a bounded deque: a new append on a full deque silently drops from the opposite end. That is a sliding window of the last n events without a separate trim.
extend and extendleft add many items. extendleft reverses the incoming order because each item is appended on the left in turn. rotate(k) moves items from one end to the other. clear empties it.
Thread safety: a deque's append and popleft are documented as atomic in CPython, which is why queue.Queue is built on one. That is not a reason to skip a lock for a larger invariant. For a simple producer/consumer between threads, queue.Queue still has the blocking and timeout API you want.
Use a deque for BFS (popleft the current node, append neighbours), for a work queue, and for a maxlen history. Use a list when you need indexing, slicing, or sort. Use queue.Queue or asyncio.Queue when you need backpressure across threads or tasks.
Iteration walks left to right, the same as a list. in is O(n). There is no slice assignment. deque[0] and deque[-1] are O(1); deque[k] for a middle k is not.
Code Examples
from collections import deque
pending = deque(["login", "pay"])
pending.append("ship") # right end
pending.appendleft("auth") # left end
print(pending.popleft()) # auth
print(pending.pop()) # ship
print(list(pending)) # ['login', 'pay']# maxlen drops from the opposite end.
window = deque(maxlen=3)
for n in range(5):
window.append(n)
print(list(window)) # [2, 3, 4]# BFS over a tiny graph stored as a dict of lists.
graph = {"a": ["b", "c"], "b": ["d"], "c": [], "d": []}
seen = {"a"}
q = deque(["a"])
order = []
while q:
node = q.popleft()
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
print(order) # ['a', 'b', 'c', 'd']Common Gotchas
`list.pop(0)` is not a queue
it is O(n). Use `deque.popleft`.
`extendleft` reverses
`d.extendleft([1, 2, 3])` yields `3, 2, 1` on the left. Reverse first if you need the original order.
Middle indexing is slow
a deque is not a list. Copy to a list if you need many random reads.
`maxlen` drop is silent
you do not get an exception when the oldest item disappears. That is the feature.