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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

9 lines
Python 3.9+
def 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

stdout
[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

  1. Use `itertools.islice` with a tee-based approach for iterators instead of sliceable sequences
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.