Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Last active December 9, 2023 18:41
Show Gist options
  • Save nathan-cruz77/2568ae0293b9685b75fa803e850fb3d9 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/2568ae0293b9685b75fa803e850fb3d9 to your computer and use it in GitHub Desktop.
Sliding window for iterables.
from itertools import islice
# Slides through iterable each `n` elements.
#
# Sample usage:
#
# >>> list(sliding_window([1, 2, 3, 4]))
# [(1, 2), (2, 3), (3, 4)]
#
# >>> list(sliding_window([1, 2, 3]))
# [(1, 2), (2, 3)]
#
# >>> list(sliding_window([1, 2, 3, 4], n=3))
# [(1, 2, 3), (2, 3, 4)]
#
def sliding_window(iterable, n=2):
args = [islice(iter(iterable), i, None) for i in range(n)]
return zip(*args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment