split_iterable

pyhelpers.ops.split_iterable(iterable, chunk_size)[source]

Split an iterable into evenly sized chunks.

See also [OPS-SI-1].

Parameters:
  • iterable (Iterable) – Iterable object to be split.

  • chunk_size (int) – Size of each chunk.

Returns:

A generator yielding chunks of size chunk_size from iterable.

Return type:

Generator[Iterable]

Examples:

>>> from pyhelpers.ops import split_iterable
>>> import pandas
>>> iterable_1 = list(range(0, 10))
>>> iterable_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> iterable_1_ = split_iterable(iterable_1, chunk_size=3)
>>> type(iterable_1_)
generator
>>> for dat in iterable_1_:
...     print(list(dat))
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
>>> iterable_2 = pandas.Series(range(0, 20))
>>> iterable_2
0      0
1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10    10
11    11
12    12
13    13
14    14
15    15
16    16
17    17
18    18
19    19
dtype: int64
>>> iterable_2_ = split_iterable(iterable_2, chunk_size=5)
>>> for dat in iterable_2_:
...     print(list(dat))
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]