Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Last active December 9, 2023 18:31
Show Gist options
  • Save nathan-cruz77/82feff6406fa061cfb7a09646d8a06a6 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/82feff6406fa061cfb7a09646d8a06a6 to your computer and use it in GitHub Desktop.
Group each N elements of the iterable.
from itertools import zip_longest
# Group each `n` elements of the iterable, filling with `fillvalue` if needed.
#
#
# Sample usage:
#
# >>> list(grouper([1, 2, 3, 4, 5, 6], 2))
# [(1, 2), (3, 4), (5, 6)]
#
# >>> list(grouper([1, 2, 3], 2))
# [(1, 2), (3, None)]
#
# >>> list(grouper([1, 2, 3], 2, fillvalue='fill value'))
# [(1, 2), (3, 'fill value')]
#
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment