Last active
December 9, 2023 18:31
-
-
Save nathan-cruz77/82feff6406fa061cfb7a09646d8a06a6 to your computer and use it in GitHub Desktop.
Group each N elements of the iterable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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