Python

Sliding Window Iterator

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Iterate over an iterable with a rolling window of N items. itertools.batched (Python 3.12+) gives you NON-overlapping chunks; this helper gives overlapping ones, common for moving averages or n-gram analysis.
Python
Raw
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]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.