How to Apply a Function to Sliding Window Slices in Python

This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.

Easy Python 3.6+ Aug 9, 2026 Algorithms & data structures 16 views 0 copies

Python code

10 lines
Python 3.6+
def apply_to_sliding_windows(data, window_size, func):
    return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 6]
    window_size = 3
    results = apply_to_sliding_windows(numbers, window_size, sum)
    print(results)
    results_avg = apply_to_sliding_windows(numbers, window_size, lambda w: sum(w) / len(w))
    print(results_avg)

Output

stdout
[6, 9, 12, 15]
[2.0, 3.0, 4.0, 5.0]

How it works

The function uses a list comprehension that iterates over each starting index from 0 to len(data) - window_size. For each index i, it slices the list with data[i:i + window_size] to get the current window and applies func to it. The range ensures the last complete window is included, avoiding index errors. This approach is O(n * window_size) in time and creates new slice lists, which is fine for moderate-sized data.

Common mistakes

  • Off-by-one error in the range (using `len(data) - window_size` instead of `len(data) - window_size + 1`)
  • Passing a function that expects a list but the window is a list already, yet sometimes people try to pass a non-callable
  • Using `data[i:i+window_size-1]` which creates a smaller window

Variations

  1. Use a generator expression and iterate lazily for memory efficiency on large datasets
  2. Use `itertools.islice` for a more efficient window iteration without slicing the list repeatedly

Real-world use cases

  • Computing rolling averages in financial time series data for trend analysis.
  • Smoothing sensor readings by averaging values over a short moving window in IoT applications.
  • Extracting local maxima or minima from a signal by applying a peak-detection function over each window.

Sponsored

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.