Sliding window over an iterable
Yield overlapping windows of fixed size, useful for moving averages and n-grams.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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
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.
Related snippets
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- Python Tested
Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.
- Python Tested
Read a CSV file as dictionaries
Stream CSV rows as dicts keyed by header with csv.DictReader, handling UTF-8 BOMs and quoted commas.

