Deque Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Deque runs in O(1) time and O(n) space, in Python as in every other language.
- ✓collections.deque, imported as from collections import deque. It is written in C (Modules/_collectionsmodule.c) and is a doubly linked list of fixed 64-slot blocks, not a ring buffer.
- ✓Reviewers expect deque(maxlen=n) for sliding windows rather than manual trimming, popleft() rather than pop(0), and rotate() rather than slicing and reconcatenating.
- ✓The Python trap: The block-list layout means indexing is O(n) in the middle even though d[0] and d[-1] are O(1); a for i in range(len(d)): d[i] loop is quadratic and silently so.
- ✓Each block holds 64 pointers, so appends allocate roughly once per 64 items and never copy existing elements: no amortised doubling and no O(n) resize spike, unlike list.
What Deque actually is
Deque in Python: what you actually reach for
Python implementation
from collections import deque
# maxlen makes a bounded sliding window: pushing at one end
# silently discards from the other. No manual trimming.
window = deque(maxlen=3)
for x in (1, 2, 3, 4):
window.append(x)
assert list(window) == [2, 3, 4]
d = deque([2, 3])
d.appendleft(1) # O(1), unlike list.insert(0, x)
d.append(4)
assert d.popleft() == 1 and d.pop() == 4
# extendleft reverses: each item is appendleft'ed in turn.
d2 = deque()
d2.extendleft([1, 2, 3])
assert list(d2) == [3, 2, 1]
d.rotate(1) # O(k) in the rotation amount; -1 rotates the other way
# Middle indexing is O(n): this loop is quadratic.
# for i in range(len(d)): use(d[i]) # don't
for item in d: # O(n) total; mutating here raises RuntimeError
pass
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Deque?
collections.deque, imported as from collections import deque. It is written in C (Modules/_collectionsmodule.c) and is a doubly linked list of fixed 64-slot blocks, not a ring buffer. appendleft, popleft, append, pop, extendleft, rotate(n) and maxlen are all real; maxlen makes it a bounded sliding window that discards from the opposite end. It is the queue primitive under asyncio.Queue and queue.Queue. Do not use list.pop(0) or list.insert(0, x): those are O(n) memmove. For a priority ordering reach for heapq instead; deque has no ordering.
What is the most common Python mistake when implementing Deque?
The block-list layout means indexing is O(n) in the middle even though d[0] and d[-1] are O(1); a for i in range(len(d)): d[i] loop is quadratic and silently so. Second, deque is thread-safe only for the single append/pop operations that the GIL makes atomic; a check-then-pop pair is a race, and popleft on an empty deque raises IndexError rather than blocking, which is why queue.Queue wraps it with a Condition. Third, extendleft reverses its input: deque().extendleft([1,2,3]) yields 3,2,1. Finally, mutating during iteration raises RuntimeError: deque mutated during iteration.
How does Deque actually perform in Python?
Each block holds 64 pointers, so appends allocate roughly once per 64 items and never copy existing elements: no amortised doubling and no O(n) resize spike, unlike list. Memory is 8 bytes per slot plus a PyObject per element, so a deque of small ints costs far more than an array module array. Locality is per-block only: a scan crosses a pointer chase every 64 items. rotate(n) costs O(k) in the rotation amount k, not O(len(d)): it moves items between the two ends in chunks, linking and freeing blocks as the rotation crosses block boundaries, so a small rotation of a huge deque stays cheap. Every append is a refcount increment. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.