In this article, we will see how to implement a sliding window or rolling iterator in Python.

Assume we have a sequence of elements and we want to process the data in a fixed length every time. In such a case, we can use the sliding window mechanism where a sliding window of k size moves over the sequence by considering the subset of k elements at each step.

The window starts at the first k element and then slides to the next k element until it reaches the end of the sequence.

Implementing sliding window iterator

def sliding_window(sequence, window_size):
    for i in range(len(sequence) - window_size + 1):
        yield sequence[i:i + window_size]

In the above example, we defined a function called sliding_window which takes two arguments i.e. sequence & window size. Using for loop we iterate over the indices of the sequence starting from 0 till len(sequence) - window_size

While iterating, we yield the sequence of the current window position which generates a new window of elements at each iteration.

Following is an example of how to use the above function:

# Example 1: Sliding window over a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7]
window_size = 3

for window in sliding_window(numbers, window_size):
    print(window)

Output:

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]

Categorized in:

Tagged in: