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.
Python code
10 linesdef 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
[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
- Use a generator expression and iterate lazily for memory efficiency on large datasets
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.