Skip to content

Commit 18cf4bf

Browse files
author
manas-shinde
committed
feat : Added new generator - batched_iterable.
1 parent 8a46d1f commit 18cf4bf

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

generators/batched_iterable.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def batched_iterable(iterable, batch_size: int):
2+
"""Yields items from iterable in batches of `batch_size`."""
3+
batch = []
4+
for item in iterable:
5+
batch.append(item)
6+
if len(batch) == batch_size:
7+
yield batch
8+
batch = []
9+
if batch:
10+
yield batch

tests/test_batched_iterable.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from generators.batched_iterable import batched_iterable
2+
3+
4+
def test_batches():
5+
data = list(range(10))
6+
batches = list(batched_iterable(data, 4))
7+
assert batches == [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

0 commit comments

Comments
 (0)