Sub topic 7
Keeping only recent items: maxlen and rotate
This chapter covers two features of collections.deque that turn it from a plain double-ended queue into a tool for sliding windows and cyclic sequences. The maxlen argument limits how many items a deque holds. The rotate() method shifts items around the deque without removing any.
It assumes you can already use deque with append, appendleft, pop, and popleft, and that you know basic Python iteration and generators. Everything here uses only the standard library.
The problem maxlen solves
Many programs need "the last N things". Examples are the last 100 log lines, the last 5 sensor readings, and the last 10 commands a user typed. With a plain list you end up writing the same bookkeeping each time:
history = []
LIMIT = 3
for n in range(5):
history.append(n)
if len(history) > LIMIT:
history.pop(0)
print(history) # [2, 3, 4]This works, but pop(0) on a list shifts every remaining item, so each trim costs time proportional to the list length. You also have to remember the trim step everywhere you add items. A bounded deque moves that rule into the container.
Creating a bounded deque
Pass maxlen when you construct the deque:
from collections import deque
recent = deque(maxlen=3)
print(recent.maxlen) # 3
for n in range(5):
recent.append(n)
print(n, list(recent))The output is:
3
0 [0]
1 [0, 1]
2 [0, 1, 2]
3 [1, 2, 3]
4 [2, 3, 4]Until the deque holds three items, it behaves like an unbounded one. After that, each append on the right removes the leftmost item first. The deque never exceeds maxlen, and it does not raise an error or warn you when it discards something.
Which end loses items
The discarded item always comes from the end opposite to where you add. This matters when you use both ends:
from collections import deque
d = deque([1, 2, 3], maxlen=3)
d.appendleft(0)
print(d) # deque([0, 1, 2], maxlen=3)
d.append(9)
print(d) # deque([1, 2, 9], maxlen=3)appendleft(0) pushes 3 off the right end. The next append(9) pushes 0 off the left end. If you only ever add on the right, the oldest item is always the one that goes, which is what you want for a "most recent items" window.
Rules and edge cases
These rules cover the cases where maxlen behaves differently from what you might guess:
| Situation | Result |
|---|---|
| `deque()` with no `maxlen` | `d.maxlen` is `None`. The deque is unbounded. |
| `deque(maxlen=0)` | Valid. Every append is discarded immediately, and the deque stays empty. |
| `deque(maxlen=-1)` | Raises `ValueError`. |
| `deque(range(10), maxlen=3)` | Starts with `deque([7, 8, 9], maxlen=3)`. The initial iterable is trimmed too. |
| `d.extend(iterable)` | Behaves like repeated `append`. Only the last `maxlen` items survive. |
| `d.extendleft(iterable)` | Behaves like repeated `appendleft`. Items are added one at a time, so they end up in reverse order. |
| `d.insert(i, x)` on a full bounded deque | Raises `IndexError`. `insert` never discards items to make room. |
| `d.maxlen = 5` | Raises `AttributeError`. `maxlen` is read-only. |
You can check a few of these directly:
from collections import deque
print(deque(range(10), maxlen=3)) # deque([7, 8, 9], maxlen=3)
zero = deque(maxlen=0)
zero.append(1)
print(zero) # deque([], maxlen=0)
full = deque([1, 2, 3], maxlen=3)
try:
full.insert(1, 99)
except IndexError as exc:
print("IndexError:", exc) # IndexError: deque already at its maximum sizeWorked example: a moving average
A moving average over the last window values needs exactly the behavior of a bounded deque. You could recompute sum(buf) / len(buf) on every step, but that costs time proportional to the window size each time. Keeping a running total is cheaper. To keep it correct, you need to know which value is about to be evicted:
from collections import deque
def moving_average(values, window):
buf = deque(maxlen=window)
total = 0
for v in values:
if len(buf) == window:
total -= buf[0] # this value is about to be discarded
buf.append(v)
total += v
yield total / len(buf)
print(list(moving_average([10, 20, 30, 40, 50], 3)))
# [10.0, 15.0, 20.0, 30.0, 40.0]Here is what happens at each step:
- For the first three values the deque is not full. The average is taken over 1, 2, then 3 items.
- When
40arrives, the deque is full, so10is subtracted from the total before the append evicts it. The total becomes30 + 40 + 20 = 90, so the average is30.0. - When
50arrives,20leaves in the same way. The total is120and the average is40.0.
Reading buf[0] on a deque is fast because it is an end of the deque. This is the pattern to use whenever you must know the value being evicted: read the end before you append.
Also, the guard len(buf) == window only works when window is at least 1. With maxlen=0 the buffer is always empty, so there is nothing to read at index 0 and no meaningful average.
Worked example: the last N lines of a file
A file object yields its lines one at a time, so feeding it to a bounded deque keeps only the last lines. The rest are read and thrown away, so memory use stays small even for a huge file. This example uses io.StringIO so that it runs without an input file:
import io
from collections import deque
text = "one\ntwo\nthree\nfour\nfive\n"
last_two = deque(io.StringIO(text), maxlen=2)
print([line.rstrip("\n") for line in last_two]) # ['four', 'five']With a real file, replace io.StringIO(text) with an open file object, for example deque(open(path, encoding="utf-8"), maxlen=2). The constructor consumes the whole iterable, so this reads the entire file once, but it never holds more than maxlen lines.
Rotating a deque
rotate(n) shifts every item n positions. Nothing is added or removed, and the length stays the same.
- A positive
nrotates to the right. Items from the right end wrap around to the left end. - A negative
nrotates to the left. Items from the left end wrap around to the right end. rotate()with no argument isrotate(1).
from collections import deque
d = deque([1, 2, 3, 4, 5])
d.rotate(2)
print(d) # deque([4, 5, 1, 2, 3])
d.rotate(-2)
print(d) # deque([1, 2, 3, 4, 5])
d.rotate(-1)
print(d) # deque([2, 3, 4, 5, 1])
d.rotate(0)
print(d) # deque([2, 3, 4, 5, 1])Rotating by 1 is the same as d.appendleft(d.pop()). Rotating by -1 is the same as d.append(d.popleft()). The method form is shorter and handles larger shifts in one call.
A shift larger than the length wraps around. On a deque of 5 items, rotate(7) gives the same result as rotate(2). Rotating an empty deque does nothing and does not raise an error.
The spine example from the earlier deque chapter shows the same behavior on a smaller scale. After the pops, the deque holds 1, 2, 3, and rotate(1) moves the last item to the front:
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d) # deque([0, 1, 2, 3, 4])
print(d.popleft()) # 0
print(d.pop()) # 4
d.rotate(1)
print(d) # deque([3, 1, 2])Worked example: round-robin scheduling
A common use of rotate is cycling through a set of choices, such as servers that should share requests evenly. Look at the front item, use it, then rotate it to the back:
from collections import deque
servers = deque(["a", "b", "c"])
picks = []
for _ in range(5):
picks.append(servers[0])
servers.rotate(-1)
print(picks) # ['a', 'b', 'c', 'a', 'b']
print(list(servers)) # ['c', 'a', 'b']After five picks, the deque has been rotated left five times. That is equivalent to rotating left twice, since three rotations return it to the start, so the front item is now 'c'. The deque remembers where the cycle stands, so you can stop and resume later. Adding a server with append places it at the end of the current cycle order.
Rotation never discards items
A bounded deque keeps all its items under rotate, because the length does not change:
from collections import deque
d = deque([1, 2, 3], maxlen=3)
d.rotate(1)
print(d) # deque([3, 1, 2], maxlen=3)Only operations that add items can trigger the maxlen eviction. Rotation, pop, and popleft never do.
Gotchas
Silent eviction hides data loss
A bounded deque will never tell you it dropped something. If that matters, for example when you need to write evicted items to disk, check before you append:
from collections import deque
buf = deque(maxlen=3)
evicted = []
for n in range(6):
if len(buf) == buf.maxlen:
evicted.append(buf[0])
buf.append(n)
print(list(buf)) # [3, 4, 5]
print(evicted) # [0, 1, 2]Copying keeps the bound, rebuilding does not
d.copy() and copy.copy(d) produce a deque with the same maxlen. Calling deque(d) builds a new deque from the items only, and it is unbounded unless you pass maxlen again:
from collections import deque
d = deque([1, 2, 3], maxlen=3)
print(d.copy().maxlen) # 3
print(deque(d).maxlen) # NoneAn unbounded copy can then grow without limit, which defeats the reason you used maxlen.
Do not mutate while iterating
Looping over a deque while you append to it or rotate it raises RuntimeError: deque mutated during iteration. This applies to bounded deques too, since an append on a full deque changes it. If you need to loop and modify, iterate over list(d) or a copy.
Indexing in the middle is slow
d[0] and d[-1] are fast. d[i] for an index near the middle takes time proportional to the distance from the nearest end. Do not pick a bounded deque for a large window if you need frequent random access into it. A list or a fixed-size ring buffer built on a list fits that case better. Slicing is not supported at all, so d[1:3] raises TypeError. Use itertools.islice(d, 1, 3) if you need a slice.
Full-window checks use len, not truthiness
A deque is falsy when empty and truthy otherwise, so if buf: tells you "has anything", not "is full". For "is the window full", compare len(buf) == buf.maxlen. On an unbounded deque maxlen is None, so that comparison is always False.
Summary of the new tools
| Tool | What it does | Typical use |
|---|---|---|
| `deque(maxlen=n)` | Holds at most `n` items and drops from the opposite end when full | Last N items, sliding windows |
| `d.maxlen` | Read-only limit, or `None` | Checking whether the window is full |
| `d.rotate(n)` | Shifts items right for positive `n` and left for negative `n`, keeping all of them | Round-robin, cyclic order |
| `d.copy()` | Shallow copy that keeps `maxlen` | Snapshots of a window |
Exercise
A bounded deque is created with d = deque([1, 2, 3, 4], maxlen=3). What does d contain, and what does d look like after d.appendleft(0)?
Show answer
The constructor trims the initial iterable to the last three items, so d is deque([2, 3, 4], maxlen=3). After appendleft(0), the rightmost item is discarded and the result is deque([0, 2, 3], maxlen=3).
Exercise
Starting from d = deque(["a", "b", "c", "d"]), which call turns it into deque(['c', 'd', 'a', 'b']), and what is another call that gives the same result?
Show answer
d.rotate(2) moves the last two items to the front. d.rotate(-2) gives the same result here, because on four items a shift of 2 to the right and a shift of 2 to the left land in the same place.
Exercise
Write a function last_unique(items, n) that returns the last n items from an iterable as a list, using a deque. Then explain why deque(items, maxlen=n) is better than building a full list and slicing it with [-n:] when items is a very large stream.
Show answer
def last_unique(items, n): return list(deque(items, maxlen=n)). The deque version holds at most n items at any time, so memory use is bounded by n. Building a full list and slicing stores every item before it throws most of them away, and it fails outright on an endless stream.
Exercise
You use deque(maxlen=3) as a window and call buf.insert(1, "x") when the window is full. What happens, and how can you get "insert and drop the oldest" behavior instead?
Show answer
insert raises IndexError because a full bounded deque refuses to insert in the middle. To get the behavior you want, call buf.popleft() first to make room, then call buf.insert(1, "x"). Alternatively, convert to a list, insert, and trim, but that costs more.