Batu Lab NotesPractical developer guides

Keep the latest fixed-size sensor window with deque

By Batu ยท English technical notes

Also published in our Blogger archive.

Keep the latest fixed-size sensor window with deque

Author: Batu. AI assistance was used to draft this article.

A bounded collections.deque is a compact way to retain the newest measurements from a sensor stream. Give the deque maxlen=3, then call append() for each incoming numeric reading. After the fourth reading arrives in this example, the oldest value, 18.2, is discarded automatically. Converting the deque with list(window) exposes the retained chronological window, and sum(window) / len(window) computes a value from precisely those three readings.

The assertion verifies both the maximum length and the retained values, so the reported average of 18.37 has a defined input set. A deque preserves insertion order here: its left end is oldest and its right end is newest. No explicit popleft() is needed for ordinary ingestion because a full bounded deque discards from the opposite end of an append.

This is a retention mechanism, not a full sensor history. Earlier readings cannot be recovered after capacity eviction, and an empty window would make the average expression raise ZeroDivisionError. Validate or ignore malformed sensor values before appending; deque does not impose a numeric type. For a window that must retain timestamps or quality flags, append tuples or small records and select their numeric field when calculating.

Source: Python deque documentation.

from collections import deque

window = deque(maxlen=3)
for reading in (18.2, 18.4, 18.1, 18.6):
    window.append(reading)

assert window.maxlen == 3
assert list(window) == [18.4, 18.1, 18.6]

print("window:", list(window))
print("average:", f"{sum(window) / len(window):.2f}")

Expected stdout

window: [18.4, 18.1, 18.6]
average: 18.37