Skip to content
GreenSnippets

Sliding window over an iterable

Yield overlapping windows of fixed size, useful for moving averages and n-grams.

Python
from collections import deque
from itertools import islice


def sliding_window(iterable, size):
    if size < 1:
        raise ValueError("size must be >= 1")
    iterator = iter(iterable)
    window = deque(islice(iterator, size), maxlen=size)
    if len(window) == size:
        yield tuple(window)
    for item in iterator:
        window.append(item)
        yield tuple(window)

Example / expected output

Output
list(sliding_window([1, 2, 3, 4], 2))  # [(1, 2), (2, 3), (3, 4)]

How it works

A deque with maxlen drops the oldest item automatically, so each step is O(1) and the iterable is consumed lazily. Python 3.10+ has itertools.pairwise for windows of two.