Skip to content
Advertisement

Rolling or sliding window iterator?

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. (Default Python iteration could be considered a special case, where the window length is 1.) I’m currently using the following code. How can I do it more elegantly and/or efficiently?

JavaScript

For the specific case of window_size == 2 (i.e., iterating over adjacent, overlapping pairs in a sequence), see also How can I iterate over overlapping (current, next) pairs of values from a list?.

Advertisement

Answer

There’s one in an old version of the Python docs with itertools examples:

JavaScript

The one from the docs is a little more succinct and uses itertools to greater effect I imagine.


If your iterator is a simple list/tuple a simple way to slide through it with a specified window size would be:

JavaScript

Output:

JavaScript
Advertisement