collections.deque
Queue Operations in Python
Master the double-ended queue from Python's standard library: use append and popleft to build efficient, production-ready FIFO queues.
What Is a Queue?
A queue is a data structure that follows the First-In, First-Out (FIFO) principle. Just like a line at a store: the first person who arrives is the first person served.
Why Not a Plain List?
Python lists can technically work as queues, but removing from the front is slow. When you call list.pop(0), every remaining element must shift left by one position.
Introducing collections.deque
deque (pronounced "deck") stands for double-ended queue. It lives in Python's built-in collections module and supports efficient appends and pops from both ends.
The Core Pattern: append + popleft
To use a deque as a FIFO queue, you only need two methods:
deque at a Glance
deque vs list
| deque | list | |
|---|---|---|
| append (right) | \( O(1) \) | \( O(1) \) amortized |
| pop (right) | \( O(1) \) | \( O(1) \) |
| popleft / pop(0) | \( O(1) \) | \( O(n) \) |
| appendleft / insert(0,x) | \( O(1) \) | \( O(n) \) |
| Random access q[i] | \( O(n) \) | \( O(1) \) |
| Best for queues? | ✓ Yes | ✕ No |
How to Build a Queue with deque
from collections import dequeq = deque() or pass an iterable.q.append(item) to add to the rear.q.popleft() to remove from the front.while q: or len(q) > 0 before popping.Example 1: Basic Queue Operations
Example 2: Print Job Queue
Example 3: BFS with deque
Breadth-First Search is the classic algorithm that relies on a queue. deque makes BFS both clean and efficient.
Bonus: maxlen for Bounded Queues
Pass a maxlen argument to limit the deque size. When full, adding to one end automatically discards from the other.
Peeking at the Front
Sometimes you want to check what's at the front without removing it. deque supports indexing, so you can peek directly:
Common Mistakes to Avoid
if q: first.Quick Reference Summary
| Operation | Code | Time | Purpose |
|---|---|---|---|
| Create | deque() |
\( O(1) \) | Initialize |
| Enqueue | q.append(x) |
\( O(1) \) | Add to rear |
| Dequeue | q.popleft() |
\( O(1) \) | Remove front |
| Peek front | q[0] |
\( O(1) \) | See front |
| Check empty | len(q) == 0 |
\( O(1) \) | Guard pops |
| Bounded | deque(maxlen=n) |
\( O(1) \) | Auto-evict |
Question 1 of 5
What is the time complexity of deque.popleft()?
Question 2 of 5
Which pair of methods creates a FIFO queue with deque?
Question 3 of 5
What happens when you call popleft() on an empty deque?
if q: before popping.Question 4 of 5
Given the code below, what is the value of result?q = deque([10, 20, 30])
q.append(40)
result = q.popleft()
Question 5 of 5
What does deque(maxlen=3) do when a fourth element is appended?