Sub topic 7
Keeping only recent items: maxlen and rotate
This chapter assumes you know basic deque operations (append, appendleft, pop, popleft) and the difference between a list and a queue. It covers two features: the maxlen argument, which bounds a deque, and rotate, which shifts its items in place.
Bounded deques with maxlen
A deque accepts an optional maxlen argument. When set, the deque never holds more than maxlen items. If you add an item to a full deque, the deque discards an item from the opposite end to make room.
from collections import deque
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(recent) # deque([2, 3, 4], maxlen=3)The loop appends 0 through 4. After 0, 1, and 2 the deque is full. Appending 3 pushes out 0 from the left. Appending 4 pushes out 1. Only the three newest items remain.
The discarded item is dropped without any error or warning. This is useful when you only care about recent data, such as the last few log lines or the last few readings from a sensor.
Which end loses items
The end that loses an item is always the opposite of the end you add to.
| Operation on a full deque | Item discarded |
|---|---|
| `append(x)` | leftmost item |
| `appendleft(x)` | rightmost item |
| `extend(items)` | leftmost items, one per added item |
| `extendleft(items)` | rightmost items, one per added item |
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)If you pass an iterable to the constructor that is longer than maxlen, the same rule applies as it fills. Only the last maxlen items survive.
from collections import deque
d = deque(range(10), maxlen=4)
print(d) # deque([6, 7, 8, 9], maxlen=4)
print(d.maxlen) # 4The maxlen attribute is read-only. It is None for an unbounded deque. To change the limit, build a new deque from the old one.
A worked example: a moving average
A bounded deque is a natural fit for a sliding window. This function keeps the last size readings and reports their average each time a new one arrives.
from collections import deque
def moving_average(values, size):
window = deque(maxlen=size)
for value in values:
window.append(value)
yield sum(window) / len(window)
print(list(moving_average([10, 20, 30, 40, 50], 3)))
# [10.0, 15.0, 20.0, 30.0, 40.0]For the first two readings the window is not yet full, so the average covers fewer than three values. From the third reading on, each append silently drops the oldest value. You write no code to trim the window.
Shifting items with rotate
rotate(n) moves items around the deque as if it were a ring. A positive n moves items from the right end to the left end. A negative n moves items from the left end to the right end.
from collections import deque
d = deque([1, 2, 3, 4, 5])
d.rotate(1)
print(d) # deque([5, 1, 2, 3, 4])
d.rotate(-2)
print(d) # deque([2, 3, 4, 5, 1])The first call moves the last item, 5, to the front. The second call moves the first two items, 5 and 1, to the back.
Rotation changes the deque in place and returns None. Nothing is discarded, so the length stays the same. Calling rotate(0) does nothing.
A common use is a round-robin: take the item at the front, use it, then move it to the back.
from collections import deque
servers = deque(["a", "b", "c"])
for _ in range(5):
print(servers[0], end=" ")
servers.rotate(-1)
print() # a b c a bCommon errors
- Expecting an error when a bounded deque is full.
appendnever raises on a full deque. If you need to know that an item was lost, checklen(d) == d.maxlenbefore you append. - Confusing rotation direction.
rotate(1)is a right rotation. To move the front item to the back, userotate(-1). - Using
maxlen=0. This is legal, but the deque always stays empty, because every append discards immediately. - Trying to set
d.maxlen = 5. The attribute is read-only and raisesAttributeError. Create a new deque withdeque(d, maxlen=5).
Exercise
Given d = deque([1, 2, 3, 4], maxlen=4), what does d look like after d.appendleft(0) followed by d.rotate(1)?
Show answer
After appendleft(0), the right end loses 4, so d is deque([0, 1, 2, 3], maxlen=4). Then rotate(1) moves the last item to the front, giving deque([3, 0, 1, 2], maxlen=4).
Exercise
Write a function last_n(iterable, n) that returns the last n items of any iterable as a list, without storing the whole iterable in memory.
Show answer
Use a bounded deque: from collections import deque def last_n(iterable, n): return list(deque(iterable, maxlen=n)) The deque discards older items as it consumes the iterable, so memory use is limited to n items.