TIL - collections.deque with maxlen is a Zero-Effort Rolling Window
A deque with maxlen automatically discards the oldest element when the capacity is full — no manual trimming, no index math.
from collections import deque
# Keep the last 5 sensor readings
window = deque(maxlen=5)
for reading in [1, 2, 3, 4, 5, 6, 7]:
window.append(reading)
print(window) # deque([3, 4, 5, 6, 7], maxlen=5)
print(sum(window) / 5) # 5.0 — rolling average
# Also O(1) on both ends — faster than list.insert(0, x)
window.appendleft(99)
print(window) # deque([99, 3, 4, 5, 6], maxlen=5)
deque appends and pops from both ends in O(1), making it the right choice for queues, sliding windows, and history buffers.