Sub topic 9
Splitting a stream into batches
This chapter assumes you know the iterator protocol, can read islice calls, and have used generators or generator expressions. Batching is the next step after slicing and pairing. You cut a stream into consecutive chunks of a fixed size without loading the whole stream into memory.
Why batch a stream
Many tasks work better on groups than on single items. Examples are inserting 500 rows per database call, sending 100 IDs per API request, and writing a large file in chunks. A list slice like data[i:i+n] needs the whole sequence in memory, and it fails on generators. Batching an iterator avoids both problems.
itertools.batched
Python 3.12 added itertools.batched(iterable, n). It yields tuples of up to n items. Only the last tuple can be shorter.
from itertools import batched
print(list(batched('ABCDEFG', 3)))This prints [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)].
batched is lazy. It reads only as many items as one batch needs, so it works on generators of any length.
from itertools import batched
squares = (x * x for x in range(7))
for batch in batched(squares, 3):
print(batch)This prints (0, 1, 4), then (9, 16, 25), then (36,). Each batch is a tuple, so convert it with list(batch) if the next step needs a list.
The islice recipe for older Pythons
Before 3.12, the standard approach was to call islice repeatedly on one shared iterator. Each call takes the next n items. The loop stops when a call returns nothing.
from itertools import islice
def batched(iterable, n):
if n < 1:
raise ValueError("n must be at least 1")
it = iter(iterable)
while batch := tuple(islice(it, n)):
yield batch
print(list(batched('ABCDEFG', 3)))The key detail is it = iter(iterable). You must create the iterator once, outside the loop. If you called islice(iterable, n) on a list each time, every call would start from the beginning and the loop would never end.
Requiring full batches
Python 3.13 added a strict argument. With strict=True, an incomplete final batch raises ValueError instead of being returned.
from itertools import batched
try:
list(batched('ABCDEFG', 3, strict=True))
except ValueError:
print("last batch was incomplete")Use this when a short batch means corrupt input, such as fixed-width records.
Common errors
- Reusing a consumed iterator. If you pass an iterator to
batchedand read from it elsewhere, the batches skip those items. This is the same exhaustion rule from the first chapter. - The
ziptrick drops data. You may seezip(*[iter(x)] * n)used for batching. It silently discards a short final group.
print(list(zip(*[iter('ABCDEFG')] * 3)))This prints [('A', 'B', 'C'), ('D', 'E', 'F')], and 'G' is lost. Use zip_longest with a fill value if you need padding, or use batched to keep the remainder.
- Expecting lists. Batches are tuples. Code that calls
batch.append(...)fails. - Version mismatch.
from itertools import batchedraisesImportErroron Python 3.11 and earlier. Define the recipe as a fallback.
Exercise
Write a generator function sum_batches(numbers, n) that yields the sum of each batch of n items from any iterable. What does list(sum_batches(range(1, 8), 3)) return?
Show answer
Use batched and sum each tuple: from itertools import batched def sum_batches(numbers, n): for batch in batched(numbers, n): yield sum(batch) The batches are (1, 2, 3), (4, 5, 6) and (7,), so the result is [6, 15, 7].