Sub topic 15
Lists as stacks, and when to use deque instead
This chapter assumes you know list indexing, append, and pop. It also assumes you know that some list operations cost more than others. Here you will use a list as a stack, see why it makes a poor queue, and switch to collections.deque when you need a queue.
A list works well as a stack
A stack is a collection where the last item added is the first one removed. This is called last in, first out (LIFO). A list does this well because append and pop() both work at the end of the list. Neither one has to move any other items.
stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print(stack[-1]) # c (peek at the top without removing it)
print(stack.pop()) # c
print(stack.pop()) # b
print(stack) # ['a']A classic use is checking that brackets match. Each opening bracket is pushed. Each closing bracket must match the most recent opening bracket still on the stack.
def balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(balanced("[(a)]{}")) # True
print(balanced("(]")) # FalseTest if not stack before you call pop(). Calling pop() on an empty list raises IndexError.
A list works badly as a queue
A queue is first in, first out (FIFO). Items enter at one end and leave from the other. With a list, the obvious way to do this is append to add and pop(0) to remove from the front.
pop(0) is slow. A list stores its items in one block of memory. When the first item is removed, every remaining item shifts one position left. The cost grows with the length of the list, which is O(n). On a long list, calling this in a loop gets slow.
insert(0, x) has the same problem for the same reason.
Use deque for queues
collections.deque (pronounced "deck", short for double-ended queue) is built for adding and removing at both ends. append, appendleft, pop, and popleft are all O(1).
from collections import deque
q = deque([1, 2, 3])
print(q.popleft()) # 1
q.append(4)
print(list(q)) # [2, 3, 4]Costs compared
| Operation | list | deque |
|---|---|---|
| Add or remove at the right end | O(1) | O(1) |
| Add or remove at the left end | O(n) | O(1) |
| Read `x[i]` in the middle | O(1) | O(n) |
| Slicing such as `x[1:3]` | Supported | Not supported |
A deque is not a general replacement for a list. Reading from the middle is slower, and it does not support slices. Pick it when the left end matters.
Common errors
- Calling
pop()orpopleft()on an empty container raisesIndexError. Check for emptiness first. - Using
list.pop(0)in a loop over a large list. Switch todequeandpopleft(). - Slicing a deque.
q[1:3]raisesTypeError. Convert withlist(q)first.
Exercise
You process 100,000 tasks in order, adding new tasks at the end and always taking the next task from the front. Which structure should you use, and why is a plain list a poor choice?
Show answer
Use collections.deque with append and popleft. A list's pop(0) shifts every remaining item left, so each removal costs O(n). popleft on a deque is O(1).