Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

collections.deque

Maintains efficient insertions and removals at both ends of a double-ended queue.

Version: Python 3.14; repository image, production runtime not attested

Syntax

collections.deque(iterable=(), maxlen=None)

Maintains efficient insertions and removals at both ends of a double-ended queue.

Appending to a full bounded queue discards an element from the opposite end.

Use append and pop at the right or appendleft and popleft at the left, all with roughly constant cost. With maxlen set, appending at capacity discards one item at the opposite end. Popping an empty deque raises IndexError. Appending 5 removes 2; then appending 1 at the left removes 5. Individual appends and pops at either end are thread-safe; sequences of operations are not atomic. On a full bounded deque insert raises IndexError without eviction, while maxlen=0 keeps the deque permanently empty.

from collections import deque
d = deque([1, 2], maxlen=2)
d.appendleft(0)
assert list(d) == [0, 1] and d.pop() == 1
d.clear()
try:
    d.popleft()
except IndexError:
    pass
else:
    raise AssertionError
z = deque(maxlen=0)
z.append(1)
assert list(z) == []
d = deque([1], maxlen=1)
try:
    d.insert(0, 2)
except IndexError:
    assert list(d) == [1]
else:
    raise AssertionError

collections.deque.append · collections.deque.pop · collections.deque.popleft

append(x) adds at the right, evicting the leftmost item when maxlen is full. pop() removes and returns the rightmost item and popleft() the leftmost. Both removal methods raise IndexError on an empty deque.

from collections import deque
q = deque([1, 2], maxlen=2)
assert q.append(3) is None and list(q) == [2, 3]
assert q.popleft() == 2 and q.pop() == 3
for remove in (q.pop, q.popleft):
    try: remove()
    except IndexError: pass
    else: raise AssertionError

Examples

import collections
q = collections.deque([2, 3], maxlen=2)
q.append(5)
print(list(q))
q.appendleft(1)
print(list(q))

Result

[3, 5]
[1, 3]

Use append and pop at the right or appendleft and popleft at the left, all with roughly constant cost. With maxlen set, appending at capacity discards one item at the opposite end. Popping an empty deque raises IndexError. Appending 5 removes 2; then appending 1 at the left removes 5. Individual appends and pops at either end are thread-safe; sequences of operations are not atomic. On a full bounded deque insert raises IndexError without eviction, while maxlen=0 keeps the deque permanently empty.

Sources