Python · Double-ended queue · container

collections.deque

A double-ended queue with O(1) appends and pops at both ends; the standard queue and stack in Python.

from collections import deque
class collections.deque(iterable=(), maxlen=None)

CPython 3.14 (maxlen since 2.6)

Operations

OperationTimeWorst caseChanges the collection
appendO(1)O(1)Yes
appendleftO(1)O(1)Yes
popleftO(1)O(1)Yes
pop / d[-1]O(1)O(1)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
In CPython, a doubly linked list of fixed-size blocks (64 references each), so both ends grow without moving existing elements.
Ordering
Sequence order, left to right.
Duplicates
Allowed.
Mutability
Mutable. With maxlen, appending to a full deque discards an element from the opposite end. Mutating during iteration raises RuntimeError.
Memory and ownership
Memory grows in blocks; no large reallocation ever copies the contents.
Equality and comparison
`in`, count and remove use ==.

Pitfalls

  • Indexing is O(1) at both ends but O(n) in the middle; a deque is not a random-access array.
  • pop and popleft on an empty deque raise IndexError.
  • Slicing is not supported (use itertools.islice).

Alternatives

  • queue.Queue for producer/consumer threads (adds locking)
  • list when you only work at the right end
  • heapq for priorities

In other languages

References