chunked

emlib.iterlib.chunked(iterable, n, strict=False)[source]

Break iterable into lists of length n

Parameters:
  • iterable – the iterable to chunk

  • n (int) – size of each chunk

  • strict – raises an error if iterable is not divisible by n

Example:

>>> list(chunked([1, 2, 3, 4, 5, 6], 3))
[[1, 2, 3], [4, 5, 6]]

By the default, the last yielded list will have fewer than n elements if the length of iterable is not divisible by n:

>>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
[[1, 2, 3], [4, 5, 6], [7, 8]]

To use a fill-in value instead, see the grouper() recipe.

If the length of iterable is not divisible by n and strict is True, then ValueError will be raised before the last list is yielded.