Sub topic 3
Keeping Only Recent Items with `deque`
Assume you know basic dict, list, loops, functions, imports, and hashable keys. A deque is a double-ended queue. Its maxlen and rotate() methods are useful when order and recent history matter.
Keeping only recent items: `maxlen` and `rotate`
maxlen gives a deque a fixed capacity. When the deque is full, adding an item removes one from the opposite end. Appending on the right removes the oldest item on the left.
from collections import deque
recent = deque(maxlen=3)
for event in ["login", "view", "edit", "logout"]:
recent.append(event)
print(recent) # deque(['view', 'edit', 'logout'], maxlen=3)
recent.rotate(1)
print(recent) # deque(['logout', 'view', 'edit'], maxlen=3)
recent.rotate(-1)
print(recent) # deque(['view', 'edit', 'logout'], maxlen=3)A positive rotation moves items from the right to the left. A negative rotation moves items in the other direction. Rotation changes order but does not add or remove items.
`deque` versus `list`: where each is fast
A deque supports fast appends and removals at both ends. A list is fast for indexing and for adding or removing at its right end.
| Task | Best usual choice |
|---|---|
| Remove from the left repeatedly | `deque` |
| Index arbitrary positions | `list` |
| Append and pop at the right | Either |
| Keep a fixed recent history | Bounded `deque` |
Removing the first item from a list shifts every remaining item, so it usually takes linear time. popleft() on a deque does not shift the other items. A deque is less suitable for frequent middle access.
Choosing the container
Use a plain dict for key-to-value lookup. Use Counter for frequencies. Use defaultdict for grouping or accumulating values without repeated missing-key checks. Use a list for ordered data with frequent indexing. Use a deque for queue or stack behavior at either end.
Exercise
Which container is most suitable for counting words and then finding the five most common words?
Show answer
Use Counter, because it counts hashable items and provides most_common(5).