Advertisement
Intermediate Python, Data Types & Structures

What is the difference between collections.deque and a regular list for queue-like operations?

Short answer

deque (double-ended queue) provides O(1) appends and pops from BOTH ends, while a regular list's insert(0, ...) and pop(0) are O(n) because every remaining element must shift — making deque the correct choice for a FIFO queue or any structure needing efficient operations at the…

Save Python mock interview
Advertisement
AModel answer
deque (double-ended queue) provides O(1) appends and pops from BOTH ends, while a regular list's insert(0, ...) and pop(0) are O(n) because every remaining element must shift — making deque the correct choice for a FIFO queue or any structure needing efficient operations at the front.
from collections import deque

queue = deque()
queue.append(1)       # O(1): add to the right end
queue.appendleft(0)   # O(1): add to the left end
queue.popleft()        # O(1): remove from the left end

# A regular list's list.pop(0) is O(n) -- much slower for this use case
Real-world example
Implementing an efficient task queue or a sliding-window buffer that needs fast operations at both ends.
Likely follow-ups
  • What other useful deque feature lets you cap it at a fixed 'maxlen', automatically discarding old items?
Related topics