01 / 20

List vs. Deque
Choosing the Right Structure

Learn when to use Python's list and when to reach for collections.deque based on the operations your program actually performs.

Python

What Is a List?

A Python list is a dynamic array: elements are stored in a contiguous block of memory. This means every item sits right next to the previous one, like books lined up on a shelf.

[0] [1] [2] [3] [4] [5] Contiguous memory: fast random access ...

What Is a Deque?

A deque (double-ended queue) from collections.deque is a doubly linked list of fixed-size blocks. Each node points to the next and previous block, enabling fast operations at both ends.

Block A Block B Block C Block D LEFT RIGHT

Why Does This Matter?

Choosing the wrong data structure can turn an \( O(1) \) operation into an \( O(n) \) one. When your program handles millions of elements, that difference is the gap between instant and frozen.

✓ Right choice
A chat app uses deque to maintain a rolling log of the last 100 messages: constant-time appends and pops at both ends.
✕ Wrong choice
Using a list for the same task means every pop(0) shifts all remaining elements: \( O(n) \) per removal.

The Core Rule

Do you need fast ops at BOTH ends? YES Use deque NO Need random access / slicing? YES Use list

Big-O at a Glance

Operation list deque
Append (right) \( O(1) \) amortized \( O(1) \)
Pop (right) \( O(1) \) \( O(1) \)
Append (left) \( O(n) \) insert(0, x) \( O(1) \) appendleft
Pop (left) \( O(n) \) pop(0) \( O(1) \) popleft
Index access [i] \( O(1) \) \( O(n) \)
Slicing [i:j] \( O(k) \) Not supported

The Key Distinction

list: Array Model
Optimized for positional access. Great when you index, slice, or iterate with random jumps. Appending to the right is cheap, but the left is expensive.
deque: Queue Model
Optimized for end operations. Great when you push and pop from both sides (FIFO queues, BFS, sliding windows). Indexing is slow.

How to Decide

1
List your hot operations. What does the inner loop or critical path do most?
2
Check for left-end work. If you insert or remove from the front, that screams deque.
3
Check for random access. If you need my_data[i] or slicing, stick with list.
4
Consider maxlen. Deque supports a maxlen parameter for automatic eviction: ideal for rolling buffers.
5
Default to list. When in doubt, list is the safer starting point since most Python code relies on indexing.

Example 1: BFS Queue

Breadth-first search needs a FIFO queue: add to the right, remove from the left. A deque handles both in \( O(1) \).

from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) # O(1) popleft while queue: node = queue.popleft() # O(1) ! if node not in visited: visited.add(node) queue.extend(graph[node])

Example 2: Sliding Window

A sliding window of size \( k \) over an array: we need to add to the right and remove from the left as the window advances. Classic deque territory.

from collections import deque def max_sliding_window(nums, k): dq = deque() # stores indices result = [] for i, num in enumerate(nums): while dq and dq[0] < i - k + 1: dq.popleft() # evict expired while dq and nums[dq[-1]] < num: dq.pop() # maintain order dq.append(i) if i >= k - 1: result.append(nums[dq[0]]) return result

Example 3: When list Wins

A scoring system where you need to look up any player's score by rank and occasionally sort: random access dominates.

scores = [95, 87, 92, 78, 88, 91] scores.sort(reverse=True) # [95, 92, 91, 88, 87, 78] # Fast random access: O(1) top_3 = scores[:3] # [95, 92, 91] slicing! median = scores[len(scores) // 2] # O(1) index

maxlen: Deque's Superpower

Pass maxlen to create a bounded buffer. When new items arrive and the deque is full, old items are automatically evicted from the opposite end.

from collections import deque # Keep only the last 5 log entries log = deque(maxlen=5) for i in range(10): log.append(f"event_{i}") print(log) # deque(['event_5','event_6','event_7','event_8','event_9'], maxlen=5)

Visualizing the Cost Difference

When you call list.insert(0, x), every existing element must shift right by one position. With \( n \) elements, that is \( n \) copies.

BEFORE insert(0, "X"): A B C D SHIFT everything right: \( O(n) \) AFTER: X A B C D deque.appendleft("X") \( O(1) \): just link a new block list.insert(0, "X") \( O(n) \): shift every element

Common Mistakes

✕ Using list.pop(0) in a loop
Each pop(0) is \( O(n) \). In a loop of \( n \) iterations this becomes \( O(n^2) \). Use deque.popleft() instead.
✕ Indexing a deque repeatedly
deque[i] is \( O(n) \). If you access by index inside a loop, you get \( O(n^2) \). Convert to a list first.
✕ Forgetting to import deque
deque lives in collections, not builtins. Always write: from collections import deque.

Summary Comparison

Feature list deque
Memory layout Contiguous array Linked blocks
Right append/pop \( O(1) \) amortized \( O(1) \)
Left append/pop \( O(n) \) \( O(1) \)
Random access [i] \( O(1) \) \( O(n) \)
Slicing Supported Not supported
maxlen auto-evict No Yes
Best for Indexing, sorting Queues, buffers

Question 1 of 5

You are implementing a BFS traversal that repeatedly removes elements from the front of a queue. Which data structure should you use?

Question 2 of 5

What is the time complexity of accessing the element at index \( i \) in a deque of \( n \) elements?

Question 3 of 5

You need a rolling buffer that automatically discards the oldest entry when a new one is added and the buffer is full. Which approach is best?

Question 4 of 5

A program builds a leaderboard by sorting scores and then slicing the top 10. Which data structure is more appropriate?

Question 5 of 5

Consider this code that processes \( n \) items. What is its overall time complexity?