from collections import deque
from typing import Iterable, Iterator, TypeVar
T = TypeVar("T")
def sliding_window[T](items: Iterable[T], n: int) -> Iterator[tuple[T, ...]]:
it = iter(items)
window: deque[T] = deque(maxlen=n)
for _ in range(n):
try: window.append(next(it))
except StopIteration: return
yield tuple(window)
for x in it:
window.append(x)
yield tuple(window)
list(sliding_window([1, 2, 3, 4, 5], 3))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
# Moving average (last 3 values)
readings = [10, 13, 12, 18, 22]
[sum(w) / 3 for w in sliding_window(readings, 3)] # [11.67, 14.33, 17.33]
Create a free account and build your private vault. Share publicly whenever you want.