Why Lists Make Slow Queues: Python's deque
This article explains how collections.deque provides constant-time operations at both ends, measures it against a list, presents bounded deques with maxlen, and identifies the operations in which a list remains the better choice.
A Python list stores its elements in one contiguous array, which makes indexing immediate and appending at the end cheap, but removing or inserting at the front forces every other element to move one position. A queue, which adds at one end and removes at the other, is therefore the one structure that a list implements badly. The type collections.deque, a double-ended queue, solves exactly that case. The present article examines how a deque is built, measures it against a list, presents its operations at both ends, explains bounded deques with maxlen, and identifies the operations in which a list remains the better choice. Constant-time access to both ends is the secret weapon of this type.
Why a List Is a Poor Queue
The methods list.pop(0) and list.insert(0, value) take time proportional to the length of the list, because the elements behind the front must be shifted in memory. The following example compares a queue operation, removing the first element and appending a new one, on a list and on a deque of two sizes.
import timeit
for size in (10_000, 100_000):
as_list = timeit.timeit(
"q.pop(0); q.append(0)", setup=f"q = list(range({size}))", number=10_000)
as_deque = timeit.timeit(
"q.popleft(); q.append(0)",
setup=f"from collections import deque; q = deque(range({size}))", number=10_000)
print(size, as_list > 10 * as_deque)
# Output: 10000 True
# Output: 100000 True
On the test machine, with CPython 3.12, the list needed about 0.55 microseconds per operation with 10,000 elements and about 5.2 microseconds with 100,000, a tenfold increase for a tenfold size, whereas the deque stayed at about 0.02 microseconds in both cases. The difference comes from the structure: CPython stores a deque as a doubly-linked list of blocks of 64 references each, so adding or removing at either end touches only the block at that end, and no other element moves. Blocks, rather than one node per element, keep the memory overhead of the links small.
Operations at Both Ends
A deque offers the methods of a list at the right end, append, pop and extend, and their mirror images at the left end, appendleft, popleft and extendleft. The same object therefore serves as a queue (first in, first out), as a stack (last in, first out), or as both at once.
from collections import deque
from collections.abc import MutableSequence
tasks = deque(["parse", "validate"])
tasks.append("store") # Enqueue at the right.
tasks.appendleft("download") # Urgent task at the left.
print(tasks.popleft()) # Output: download
print(tasks.pop()) # Output: store
print(tasks) # Output: deque(['parse', 'validate'])
numbers = deque([1, 2, 3])
numbers.extendleft([4, 5])
print(numbers) # Output: deque([5, 4, 1, 2, 3])
numbers.rotate(1)
print(numbers) # Output: deque([3, 5, 4, 1, 2])
print(isinstance(tasks, MutableSequence)) # Output: True
extendleft appends its items one by one at the left, so they appear in reverse order, a detail that surprises on first use. rotate(n) moves the last n elements to the front, or the first ones to the back when n is negative, which turns a deque into an efficient round-robin scheduler. Being a MutableSequence, in the sense described in the article devoted to abstract base classes, a deque also supports len, in, indexing, index, count, remove, insert and reverse.
Bounded Deques with maxlen
A deque created with maxlen never grows beyond that length: when it is full, each new element pushes out one element from the opposite end. Online games offer an exact image for this behaviour in their message logs, which keep only the most recent lines and silently discard the oldest one each time a new message arrives. In the same way, deque(maxlen=n) always holds the last n items, with no explicit trimming code.
from collections import deque
history = deque(["home", "products", "cart"], maxlen=3)
history.append("checkout")
print(history) # Output: deque(['products', 'cart', 'checkout'], maxlen=3)
history.appendleft("home")
print(history) # Output: deque(['home', 'products', 'cart'], maxlen=3)
try:
history.insert(1, "search")
except IndexError as error:
print(error) # Output: deque already at its maximum size
The analogy, however, stops at this point, because a message log only discards at one end, whereas a deque discards at whichever end is opposite to the insertion: appendleft pushed out "checkout" from the right. The method insert, which places an element in the middle, has no opposite end to discard from, and it raises IndexError on a full bounded deque. Bounded deques suit sliding windows, recent-history buffers and the last lines of a file, as in deque(open(path), maxlen=10).
Pitfalls of Deques
A deque resembles a list closely enough to be used as one, yet several list operations behave differently or not at all. Five pitfalls are distinguished, which are the following:
- Slow middle access. Indexing is fast near the ends and proportional to the distance from the nearest end in the middle; on the test machine,
d[n // 2]took about 2 microseconds with 100,000 elements, against 19 nanoseconds for a list. - No slicing.
d[1:3]raisesTypeError;itertools.isliceor a conversion to a list is required. - Mutation during iteration. Adding or removing elements while iterating raises
RuntimeError. - Thread safety is limited to single calls.
appendandpopleftare atomic, but a check followed by an action, such as testinglenbeforepopleft, is not;queue.Queueadds blocking and coordination. extendleftreverses. The items of the iterable appear at the left in reverse order.
The second and third pitfalls are reproduced in the following example.
from collections import deque
from itertools import islice
window = deque(range(10))
try:
window[2:5]
except TypeError as error:
print(error) # Output (CPython 3.12): sequence index must be integer, not 'slice'
print(list(islice(window, 2, 5))) # Output: [2, 3, 4]
try:
for item in window:
window.append(item)
except RuntimeError as error:
print(error) # Output: deque mutated during iteration
The function islice, examined in the article devoted to itertools, reads the requested range lazily without copying the whole deque. The loop fails at the first step after the deque has changed, which protects the iteration from silently skipping or repeating elements.
Choosing the Right Structure
Consequently, the choice between a deque and its neighbours depends on where elements are added and removed and on who consumes them, as the following table summarizes.
| Need | Recommended structure |
|---|---|
| Random access by index, slicing, sorting | list |
| Stack with pushes and pops at the end only | list or deque |
| Queue: add at one end, remove at the other | collections.deque |
Last n items, sliding windows |
collections.deque(maxlen=n) |
| Round-robin rotation of tasks | collections.deque with rotate |
| Producer and consumer threads that must wait for each other | queue.Queue |
| Elements served by priority rather than arrival | heapq or queue.PriorityQueue |
For queues shared by threads or processes, the coordination tools described in the article devoted to concurrency are the appropriate next step.
Conclusion
It is concluded that collections.deque replaces the linear cost of list.pop(0) and list.insert(0, value) with constant-time operations at both ends, thanks to a doubly-linked list of fixed-size blocks, and that maxlen turns it into a self-trimming buffer. This magic has its price in the middle of the structure, where indexing slows down and slicing is unavailable, so a list remains the right choice for random access. Queues ordered by arrival are only one kind of queue; priority queues, which serve the smallest element first, are built with the module heapq, which is developed in a future article of this series.