01 / 20

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.

Python

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.

Queue A B C D enqueue dequeue Front (out) Rear (in)

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.

list.pop(0) : every element shifts A B C D ... N
\( O(n) \)
deque.popleft() : no shifting needed A B C D ... N
\( O(1) \)

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.

from collections import deque # Create an empty deque q = deque() # Create from an iterable q = deque(["A", "B", "C"])

The Core Pattern: append + popleft

To use a deque as a FIFO queue, you only need two methods:

q.append(x)
Add element x to the right end (rear of the queue). Runs in \( O(1) \) time.
q.popleft()
Remove and return the element from the left end (front of the queue). Runs in \( O(1) \) time.
1 2 3 4 append() popleft() Front (oldest) Rear (newest)

deque at a Glance

deque([...items...]) appendleft(x) popleft() append(x) pop() len(q) q[0] rotate(n) Left End Right End Utility Methods

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

1
Import: Write from collections import deque
2
Initialize: Create with q = deque() or pass an iterable.
3
Enqueue: Call q.append(item) to add to the rear.
4
Dequeue: Call q.popleft() to remove from the front.
5
Check empty: Use while q: or len(q) > 0 before popping.

Example 1: Basic Queue Operations

from collections import deque q = deque() q.append("Alice") # q: [Alice] q.append("Bob") # q: [Alice, Bob] q.append("Carol") # q: [Alice, Bob, Carol] first = q.popleft() # "Alice" — served first second = q.popleft() # "Bob" — served second print(q) # deque(['Carol'])

Example 2: Print Job Queue

from collections import deque print_queue = deque() # Users submit print jobs print_queue.append("report.pdf") print_queue.append("photo.jpg") print_queue.append("essay.docx") # Process jobs in order while print_queue: job = print_queue.popleft() print(f"Printing: {job}")

Example 3: BFS with deque

Breadth-First Search is the classic algorithm that relies on a queue. deque makes BFS both clean and efficient.

from collections import deque def bfs(graph, start): visited = {start} queue = deque([start]) while queue: node = queue.popleft() print(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor)

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.

recent = deque(maxlen=3) recent.append("page1") # [page1] recent.append("page2") # [page1, page2] recent.append("page3") # [page1, page2, page3] recent.append("page4") # [page2, page3, page4] — page1 dropped!
maxlen = 3 page2 page3 page4 append dropped page1 Automatically evicted when full

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:

q = deque(["Alice", "Bob", "Carol"]) # Peek at front (left end) front = q[0] # "Alice" — still in queue # Peek at rear (right end) rear = q[-1] # "Carol" — still in queue # Check size print(len(q)) # 3

Common Mistakes to Avoid

✕ Using list.pop(0)
This is \( O(n) \) because every element shifts. Use deque.popleft() instead for \( O(1) \) performance.
✕ Popping from empty deque
Calling popleft() on an empty deque raises IndexError. Always check if q: first.
✕ Mixing up append sides
Using appendleft() + pop() is a valid queue, but the convention is append() + popleft(). Pick one pattern.

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?

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?