How to Build a Sliding Window Generator in Python
Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.
Python code
9 linesdef sliding_window(sequence, size):
for i in range(len(sequence) - size + 1):
yield sequence[i:i + size]
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
n = 3
for window in sliding_window(data, n):
print(window)
Output
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
How it works
The yield keyword turns the function into a generator, producing values lazily one at a time instead of building a full list in memory. The loop for i in range(len(sequence) - size + 1) calculates the starting indexes for each window, ensuring the final slice fits exactly within the sequence. Slicing sequence[i:i + size] returns a new list or tuple for each window, preserving order and overlapping elements. This approach keeps memory usage minimal, even for very large sequences, because only one window exists at a time. It is a classic pattern for time-series analysis, signal processing, and moving-average calculations.
Common mistakes
- Using `range(len(sequence) - size)` instead of adding `+1`, which drops the last window
- Assuming the input must be a list — any sliceable sequence (string, tuple) works
- Passing a size larger than the sequence, which yields no windows without error
- Forgetting this is a generator, so it can only be iterated once unless recreated
Variations
- Use `itertools.islice` with a tee-based approach for iterators instead of sliceable sequences
- Return a list comprehension if you need all windows at once: `[sequence[i:i+size] for i in range(len(sequence)-size+1)]`
Real-world use cases
- Computing rolling means or standard deviations on time-series sensor data in financial analytics.
- Extracting overlapping n-gram windows from tokenized text for language model feature engineering.
- Smoothing audio or signal data by averaging samples over a fixed sliding frame in real-time processing.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.