Sub topic 8
Bounded deques and keeping the last N items
This chapter covers collections.deque with the maxlen argument. It assumes you know basic Python syntax, lists and indexing, and the earlier chapter on deque operations (append, appendleft, pop, popleft). By the end you should be able to keep the last N items of a stream without writing any trimming code.
The problem: remembering only recent items
Many programs need a "recent history": the last 10 log lines, the last 100 sensor readings, the last 5 commands a user typed. With a plain list you have to trim it yourself:
history = []
for n in range(5):
history.append(n)
if len(history) > 3:
history.pop(0) # O(n): every remaining item shifts left
print(history) # [2, 3, 4]This works, but the pop(0) costs O(n), and the trimming logic is easy to forget or get wrong. A bounded deque does the trimming for you in O(1).
How maxlen works
Pass maxlen when you create the deque. Once the deque holds maxlen items, adding to one end discards an item from the opposite end.
from collections import deque
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(list(recent)) # [2, 3, 4]Here is what happens at each step:
| Step | Operation | Contents after |
|---|---|---|
| 1 | `append(0)` | `[0]` |
| 2 | `append(1)` | `[0, 1]` |
| 3 | `append(2)` | `[0, 1, 2]` |
| 4 | `append(3)` | `[1, 2, 3]` (0 discarded) |
| 5 | `append(4)` | `[2, 3, 4]` (1 discarded) |
Nothing is raised when an item is dropped. The discard is silent, which is the point of the feature, but it also means you will not notice if you drop data you needed.
Which end gets discarded
The rule depends on which end you add to:
append(x)adds on the right and discards from the left.appendleft(x)adds on the left and discards from the right.extend(iterable)behaves like repeatedappendcalls. Only the lastmaxlenitems of the iterable survive.extendleft(iterable)behaves like repeatedappendleftcalls. Note that it also reverses the order of the items it adds.
from collections import deque
d = deque([1, 2, 3], maxlen=3)
d.appendleft(0)
print(d) # deque([0, 1, 2], maxlen=3)
d.extend([7, 8, 9, 10])
print(d) # deque([8, 9, 10], maxlen=3)You can read the limit back from the maxlen attribute. It is None for an unbounded deque, and it is read-only, so you cannot resize a deque after creation. To change the limit, build a new deque: deque(old, maxlen=new_size).
A practical example: moving average
A bounded deque is a natural fit for a moving average over the last N readings. The deque holds the window, and the oldest reading falls out automatically.
from collections import deque
def moving_average(values, window_size):
window = deque(maxlen=window_size)
averages = []
for v in values:
window.append(v)
averages.append(sum(window) / len(window))
return averages
print(moving_average([10, 20, 30, 40, 50], 3))
# [10.0, 15.0, 20.0, 30.0, 40.0]The first two averages use fewer than three values because the window is not yet full. Decide up front whether that is acceptable. If not, only record an average once len(window) == window_size.
Common errors
- Expecting an error when full. A bounded deque never raises on append. The
RingQueuefrom the circular-buffer chapter raisedOverflowError;deque(maxlen=...)overwrites instead. Pick the behavior your program needs. - Using
maxlen=0. This is legal, but every append is discarded immediately, so the deque is always empty. - Indexing in the middle of a large deque.
d[0]andd[-1]are O(1), butd[i]near the middle is O(n). If you need fast random access, a deque is the wrong tool. - Expecting
sum(window)to be free. In the moving average above,sumis O(N) per step. For large windows, keep a running total and adjust it as items enter and leave.
Exercise
A deque is created with d = deque([1, 2, 3, 4], maxlen=4). You then run d.appendleft(0) followed by d.extend([8, 9]). What does list(d) return, and which items were discarded along the way?
Show answer
After appendleft(0) the deque is [0, 1, 2, 3], and 4 is discarded from the right. extend([8, 9]) appends 8 and then 9 on the right, discarding 0 and then 1 from the left. The result is [2, 3, 8, 9]. The discarded items, in order, are 4, 0, and 1.
Exercise
Write a function last_lines(path, n) that returns the last n lines of a text file as a list, without loading the whole file into memory.
Show answer
Use a bounded deque and iterate over the file lazily: from collections import deque def last_lines(path, n): with open(path) as f: return list(deque(f, maxlen=n)) Iterating over the file yields one line at a time, and the deque keeps only the most recent n. Memory use is proportional to n, not to the file size.