grouper

class iteration_utilities.grouper(iterable, n, fillvalue=None, truncate=False)

Collect data into fixed-length chunks or blocks.

Parameters:

iterable : iterable

Any iterable to group.

n : int

The number of elements in each chunk.

fillvalue : any type, optional

The fillvalue if the iterable is consumed and the last yielded group should be filled. If not given the last yielded group may be shorter than the group before. Using fillvalue=None is different from not giving a fillvalue in that the last group will be filled with None.

truncate : bool, optional

As alternative to fillvalue the last group is discarded if it is shorter than n and truncate is True. Default is False.

Returns:

groups : generator

An iterable containing the groups/chunks as tuple.

Raises:

TypeError

If truncate is True and a fillvalue is given.

Examples

>>> from iteration_utilities import grouper
>>> list(grouper('ABCDEFG', 3))
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
>>> list(grouper('ABCDEFG', 3, fillvalue='x'))
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
>>> list(grouper('ABCDEFG', 3, truncate=True))
[('A', 'B', 'C'), ('D', 'E', 'F')]
__length_hint__()

Tries to estimate for the length of the instance (returns 0 if an estimation is not possible).

Note

Requires Python >= 3.4

fillvalue

(any type) The fillvalue if the last group does not contain enough items (readonly).

New in version 0.6.

times

(int) The size of each group (readonly).

New in version 0.6.

truncate

(int) True if an incomplete last group is discarded (readonly).

New in version 0.6.