ZetCode

Python deque

last modified November 30, 2026 Python 3.15

In this article we show how to use the deque type from the collections module.

A deque (pronounced deck) is a double-ended queue: a sequence that supports fast adding and removing of items at both ends. A Python list is fast only at its right end. Inserting or removing the first item of a list moves all other items, so the cost grows with the length of the list. A deque does the same in constant time, no matter how long it is.

In CPython, a deque is a doubly linked list of fixed-size blocks. This makes the ends cheap but access by index in the middle slower than in a list. A deque is therefore the right choice for queues, stacks, and windows over the latest items, while a list remains better for random access.

Creating a deque

A deque is created with the deque constructor, optionally from an iterable. The append method adds an item to the right end, appendleft to the left end.

deque_basics.py
from collections import deque

d = deque(['b', 'c'])

d.append('d')
d.appendleft('a')

print(d)
print(len(d))

We create a deque from a list of two items and add one item at each end. The deque prints as deque([...]) and supports the len function like other sequences.

$ python deque_basics.py
deque(['a', 'b', 'c', 'd'])
4

Removing items from both ends

The pop method removes and returns the rightmost item, the popleft method the leftmost one. Both raise IndexError when the deque is empty.

both_ends.py
from collections import deque

d = deque([1, 2, 3, 4, 5])

last = d.pop()
first = d.popleft()

print(first, last)
print(d)

while d:
    print(d.popleft(), end=' ')

print()
print(d)

We remove the last and the first item. The while d loop then empties the deque from the left; an empty deque is false, so the loop ends when no items are left.

$ python both_ends.py
1 5
deque([2, 3, 4])
2 3 4 
deque([])

A queue

A queue processes items in the order in which they arrived: first in, first out (FIFO). With a deque, we add items with append and take them with popleft.

fifo_queue.py
from collections import deque

waiting = deque()

waiting.append('Peter')
waiting.append('Lucy')
waiting.append('Martin')
print('waiting:', list(waiting))

print('serving', waiting.popleft())

waiting.append('Anna')
print('waiting:', list(waiting))

while waiting:
    print('serving', waiting.popleft())

Three customers join the queue and Peter, who came first, is served first. Anna arrives later and is placed at the end. A list could do the same with pop(0), but every such call would shift all the remaining items.

$ python fifo_queue.py
waiting: ['Peter', 'Lucy', 'Martin']
serving Peter
waiting: ['Lucy', 'Martin', 'Anna']
serving Lucy
serving Martin
serving Anna

A stack

A stack returns the most recently added item first: last in, first out (LIFO). It uses only the right end, with append and pop.

undo_stack.py
from collections import deque

text = ''
history = deque()

for word in ['old', 'falcon', 'flies']:
    history.append(text)
    text = (text + ' ' + word).strip()
    print(f'typed:  {text!r}')

for _ in range(2):
    text = history.pop()
    print(f'undo:   {text!r}')

We simulate the undo feature of an editor. Before each change, the current text is pushed to the history. Each undo pops the most recent state. A list works equally well as a stack, since it is fast at its right end; see Python list. A deque becomes useful when the history must also be trimmed from the other end, which is shown later with maxlen.

$ python undo_stack.py
typed:  'old'
typed:  'old falcon'
typed:  'old falcon flies'
undo:   'old falcon'
undo:   'old'

Extending a deque

The extend method appends all items of an iterable to the right end. The extendleft method adds them to the left end, one by one.

extend_both.py
from collections import deque

d = deque([4, 5])

d.extend([6, 7, 8])
print(d)

d.extendleft([3, 2, 1])
print(d)

d.extendleft(reversed([-2, -1, 0]))
print(d)

Since extendleft adds the items one at a time, each new item lands in front of the previous one, and the items end up in reverse order. Passing [3, 2, 1] therefore gives 1, 2, 3 at the start. To keep the original order, we reverse the iterable first, as in the last call.

$ python extend_both.py
deque([4, 5, 6, 7, 8])
deque([1, 2, 3, 4, 5, 6, 7, 8])
deque([-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])

Accessing items

A deque supports indexing, the in operator, iteration, and the index and count methods. It does not support slicing.

access.py
from collections import deque

d = deque(['sky', 'cup', 'pen', 'cup', 'map'])

print(d[0], d[-1])
print(d[2])

print('pen' in d)
print(d.index('cup'))
print(d.count('cup'))

for word in d:
    print(word.upper(), end=' ')

print()
print(d[1:3])

Indexing at the ends, d[0] and d[-1], is fast. Indexing towards the middle must walk through the blocks, so it is slower for long deques. The last line fails, because a deque cannot be sliced. The itertools.islice function can take a range of items from a deque instead.

$ python access.py
sky map
pen
True
1
2
SKY CUP PEN CUP MAP 
Traceback (most recent call last):
  File "/home/user/python/access.py", line 16, in <module>
    print(d[1:3])
          ~^^^^^
TypeError: sequence index must be integer, not 'slice'

Changing the middle

Items can be inserted, removed, and deleted anywhere in the deque. The deque can also be reversed in place and cleared.

middle.py
from collections import deque

d = deque(['a', 'b', 'c', 'd', 'e'])

d.insert(2, 'x')
print(d)

d.remove('x')
print(d)

del d[1]
print(d)

d.reverse()
print(d)

d.clear()
print(d)

The insert method puts an item before the given index, and remove deletes the first occurrence of a value. The del statement deletes an item by its index. These operations work like their list counterparts, and like them they are not fast in the middle of a long sequence.

$ python middle.py
deque(['a', 'b', 'x', 'c', 'd', 'e'])
deque(['a', 'b', 'c', 'd', 'e'])
deque(['a', 'c', 'd', 'e'])
deque(['e', 'd', 'c', 'a'])
deque([])

Rotating a deque

The rotate(n) method moves the items n steps to the right. Items that fall off the right end come back at the left end. A negative n rotates to the left.

rotation.py
from collections import deque

d = deque([1, 2, 3, 4, 5, 6])

d.rotate(2)
print(d)

d.rotate(-3)
print(d)

d.rotate(-1)
print(d)

Rotating right by two moves 5 and 6 to the front. Rotating left by three moves the first three items to the back. A rotation by one step to the left is the same as d.append(d.popleft()).

$ python rotation.py
deque([5, 6, 1, 2, 3, 4])
deque([2, 3, 4, 5, 6, 1])
deque([3, 4, 5, 6, 1, 2])

A counting-out game

Rotation is handy for circular problems. In this counting-out game, players stand in a circle and every third player leaves until only one remains.

counting_out.py
from collections import deque

players = deque(['Ann', 'Bob', 'Cid', 'Dan', 'Eva', 'Fay', 'Gus'])
step = 3

while len(players) > 1:
    players.rotate(-(step - 1))
    out = players.popleft()
    print(f'{out} is out, left: {list(players)}')

print('winner:', players[0])

The players are kept in a deque. Rotating to the left by step - 1 moves the counted players to the back, so the player who is out is at the front and can be removed with popleft. The counting continues from the next player in the circle. This is a version of the Josephus problem.

$ python counting_out.py
Cid is out, left: ['Dan', 'Eva', 'Fay', 'Gus', 'Ann', 'Bob']
Fay is out, left: ['Gus', 'Ann', 'Bob', 'Dan', 'Eva']
Bob is out, left: ['Dan', 'Eva', 'Gus', 'Ann']
Gus is out, left: ['Ann', 'Dan', 'Eva']
Eva is out, left: ['Ann', 'Dan']
Ann is out, left: ['Dan']
winner: Dan

A bounded deque

The maxlen argument limits the size of a deque. When a bounded deque is full, adding an item at one end drops an item from the other end.

bounded.py
from collections import deque

recent = deque(maxlen=3)

for page in ['home', 'news', 'sport', 'weather', 'mail']:
    recent.append(page)
    print(recent)

recent.appendleft('start')
print(recent)
print(recent.maxlen)

The deque keeps the three most recently visited pages. After the third page, each append pushes the oldest page out on the left. The appendleft call works the other way round and drops the item at the right end. The limit is available in the read-only maxlen attribute.

$ python bounded.py
deque(['home'], maxlen=3)
deque(['home', 'news'], maxlen=3)
deque(['home', 'news', 'sport'], maxlen=3)
deque(['news', 'sport', 'weather'], maxlen=3)
deque(['sport', 'weather', 'mail'], maxlen=3)
deque(['start', 'sport', 'weather'], maxlen=3)
3

The last lines of a file

A bounded deque built from an iterable keeps only its last items. This gives a short version of the Unix tail command.

tail.py
from collections import deque

with open('access.log') as f:
    last = deque(f, maxlen=3)

for line in last:
    print(line, end='')

The access.log file has six lines. The file object is an iterable of lines, and the deque keeps the last three of them. The earlier lines are read and dropped one by one, so memory use stays small even for very large files.

$ python tail.py
192.168.0.10 POST /login 302
192.168.0.13 GET /news.html 200
192.168.0.11 GET /favicon.ico 404

deque versus list

In this example we measure the cost of adding and removing an item at the left end of a list and of a deque, and the cost of indexing the middle of a deque.

speed.py
import timeit

for n in [10_000, 100_000, 1_000_000]:

    setup = f'from collections import deque; lst = list(range({n})); d = deque(lst)'

    t_list = timeit.timeit('lst.insert(0, 1); lst.pop(0)', setup, number=1000)
    t_deque = timeit.timeit('d.appendleft(1); d.popleft()', setup, number=1000)
    t_index = timeit.timeit(f'd[{n // 2}]', setup, number=1000)

    print(f'{n:>9}  list: {t_list:.5f} s  deque: {t_deque:.5f} s'
          f'  deque middle index: {t_index:.5f} s')

The timeit function runs each statement a thousand times. For the list, the time grows with its length, because insert(0, x) and pop(0) move all items. For the deque, the time stays the same. Indexing the middle of the deque grows with its length, which is the price for the fast ends. The timings differ from machine to machine.

$ python speed.py
    10000  list: 0.00331 s  deque: 0.00006 s  deque middle index: 0.00014 s
   100000  list: 0.02849 s  deque: 0.00004 s  deque middle index: 0.00210 s
  1000000  list: 0.69404 s  deque: 0.00004 s  deque middle index: 0.02634 s

Breadth-first search

Breadth-first search visits the nodes of a graph in order of their distance from the start. It keeps the nodes to visit in a FIFO queue, which makes it a classic use of a deque.

shortest_path.py
from collections import deque

network = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A', 'D', 'E'],
    'D': ['B', 'C', 'F'],
    'E': ['C', 'F'],
    'F': ['D', 'E', 'G'],
    'G': ['F'],
}


def shortest_path(graph, start, goal):

    previous = {start: None}
    todo = deque([start])

    while todo:
        node = todo.popleft()

        if node == goal:
            path = []
            while node is not None:
                path.append(node)
                node = previous[node]
            return path[::-1]

        for neighbour in graph[node]:
            if neighbour not in previous:
                previous[neighbour] = node
                todo.append(neighbour)

    return None


print(shortest_path(network, 'A', 'G'))
print(shortest_path(network, 'B', 'E'))

The graph is a dictionary that maps each node to its neighbours. The search takes nodes from the left end of the queue and adds newly discovered neighbours to the right end, so nearer nodes are always processed first. The previous dictionary records how each node was reached and also marks visited nodes. When the goal is found, we follow the links back to the start, which gives a path with the fewest steps.

$ python shortest_path.py
['A', 'B', 'D', 'F', 'G']
['B', 'A', 'C', 'E']

Sliding window maximum

The last example finds the maximum of every window of k consecutive values. Recomputing max for each window would take k steps per window. A deque that holds candidate positions does it with a constant amount of work per value on average.

window_max.py
from collections import deque


def window_max(values, k):

    result = []
    candidates = deque()

    for i, value in enumerate(values):

        if candidates and candidates[0] <= i - k:
            candidates.popleft()

        while candidates and values[candidates[-1]] <= value:
            candidates.pop()

        candidates.append(i)

        if i >= k - 1:
            result.append(values[candidates[0]])

    return result


temps = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

print(window_max(temps, 3))
print(window_max(temps, 5))

The deque stores indexes, and their values are kept in decreasing order. A position that has left the window is removed from the front. Before a new value is added at the back, all smaller values are popped, since they can never be a maximum again. The front of the deque is thus always the maximum of the current window. Each index is added and removed at most once. A simpler window over the latest items, with maxlen, is shown in the sliding window recipe in Python itertools.

$ python window_max.py
[4, 4, 5, 9, 9, 9, 6, 6, 5]
[5, 9, 9, 9, 9, 9, 6]

Source

collections.deque, TimeComplexity – Python Wiki

In this article we have used a deque as a queue and a stack, added and removed items at both ends, rotated it, kept the last items with maxlen, and used it for breadth-first search and a sliding window. The append and popleft methods are thread-safe, but code that shares work between threads usually needs a queue that can block and wait; for that, the standard library provides the queue module. See also Python collections, Python list, and Python infinite iterators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.