Sub topic 9
Splitting a stream into batches
Many programs need to handle data in groups instead of one item at a time. Examples include inserting database rows 500 at a time, sending API requests with 100 IDs each, or writing a large file in chunks. This chapter shows how to split any iterable into fixed-size batches without loading it all into memory.
This chapter assumes you know how islice works from the earlier chapter on slicing iterators, and that you understand that an iterator is consumed as you read it. You should also be comfortable with the walrus operator (:=) and with generator functions.
What batching means
A batch is a group of up to n consecutive items from a stream. Splitting A B C D E F G into batches of 3 gives ABC, DEF and G. The last batch is shorter because the input ran out.
Slicing a list with data[i:i+n] in a loop does the same job, but it needs a sequence that supports indexing and a known length. A file object, a generator, or a database cursor supports neither. Batching with iterators works on any iterable, and it reads only one batch ahead.
itertools.batched
Python 3.12 added itertools.batched(iterable, n). It returns an iterator that yields tuples of at most n items.
from itertools import batched
print(list(batched('ABCDEFG', 3)))This prints [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]. Three properties matter:
- Each batch is a tuple, even when the input is a string. You can use
"".join(batch)to get strings back. - Every batch has exactly
nitems except possibly the last one. - An empty input produces no batches at all, not one empty batch.
from itertools import batched
print(["".join(b) for b in batched('ABCDEFG', 3)])This prints ['ABC', 'DEF', 'G'].
A realistic use
The usual pattern is a for loop over batched. The source can be a generator, so only one batch is held in memory at a time.
from itertools import batched
def save_batch(rows):
print(f"saving {len(rows)} rows: {rows[0]}..{rows[-1]}")
rows = (f"row{i}" for i in range(1, 11))
for batch in batched(rows, 4):
save_batch(batch)The output is:
saving 4 rows: row1..row4
saving 4 rows: row5..row8
saving 2 rows: row9..row10The generator expression never builds a list of ten rows. With ten million rows, memory use would still be four rows plus overhead.
Batching infinite streams
batched is lazy, so it works on infinite iterators. Combine it with islice to stop after a number of batches.
from itertools import batched, count, islice
for batch in islice(batched(count(1), 3), 2):
print(batch)This prints (1, 2, 3) and then (4, 5, 6). Here islice limits the number of batches, not the number of items.
How the batching loop works
Before Python 3.12 there was no batched, and many codebases still support older versions. The itertools documentation gives an equivalent recipe built from islice. It is worth understanding because it shows how batched behaves.
from itertools import islice
def batched(iterable, n):
if n < 1:
raise ValueError('n must be at least one')
iterator = iter(iterable)
while batch := tuple(islice(iterator, n)):
yield batch
print(list(batched('ABCDEFG', 3)))This prints the same result as the built-in version. The loop does the following:
iter(iterable)creates one iterator that is shared by every pass of the loop.islice(iterator, n)takes up tonitems from it and advances it.tuple(...)forces those items out immediately, so the batch is a fixed value.- An empty tuple is falsy, so the
whileloop ends when the source is exhausted.
Why iter() is required
The iter(iterable) call is easy to forget, and leaving it out causes a serious bug. Each islice call must continue where the previous one stopped. A list is an iterable, not an iterator, so every islice over it starts again from the beginning.
from itertools import islice
data = [1, 2, 3, 4, 5]
print(list(islice(data, 2)))
print(list(islice(data, 2)))Both lines print [1, 2]. In a while loop, a recipe that skips iter() would never run out of items, so it would loop forever. Calling iter() once gives a single iterator whose position is remembered between calls. When the argument is already an iterator, iter() returns it unchanged, so the call is always safe.
Strict batches
By default the last batch may be short. Sometimes a short batch is an error, for example when records must come in groups of three. Python 3.13 added a strict keyword argument to batched.
from itertools import batched
try:
for batch in batched('ABCDEFG', 3, strict=True):
print(batch)
except ValueError:
print("incomplete batch")This prints ('A', 'B', 'C'), then ('D', 'E', 'F'), and then incomplete batch. The complete batches are yielded first. The error is raised only when the short final batch is reached. If you call list(...) on a strict batched, the exception discards the whole result, so use a loop if you need the complete batches.
On Python 3.12, strict does not exist and passing it raises TypeError. Check the final batch's length yourself instead:
from itertools import batched
for batch in batched('ABCDEFG', 3):
if len(batch) < 3:
print("short batch:", batch)This prints short batch: ('G',).
The older zip idiom
You may see this trick in older code:
print(list(zip(*[iter('ABCDEFG')] * 3)))It prints [('A', 'B', 'C'), ('D', 'E', 'F')]. The expression [iter(x)] * 3 makes a list holding the same iterator three times. zip then pulls one item from each in turn, so each tuple holds three consecutive items. The short last group is silently dropped because zip stops at the shortest input. Replacing zip with zip_longest keeps the tail but pads it with a fill value, which is not the same as a short batch.
This idiom is clever but hard to read, and it loses data by default. Prefer batched or the islice recipe.
Edge cases and choices
| Situation | Behavior of `batched` |
|---|---|
| Input is empty | Yields nothing |
| `n` is larger than the input | Yields one short batch |
| `n` is 0 or negative | Raises `ValueError` |
| Input is an infinite iterator | Works; batches are produced lazily |
| Input length is a multiple of `n` | All batches are full; no short batch |
Other things to keep in mind:
- Each batch is a tuple built in memory, so a very large
ndefeats the purpose of laziness. Choosenso one batch fits comfortably in memory. batchedconsumesnitems before it yields the first batch. If the source is slow, such as a network stream, the first batch is delayed untilnitems arrive.- If the source raises an error partway through a batch, the items already collected for that batch are lost.
- The batch is a snapshot. Modifying the source list later does not change batches already yielded.
Choosing between approaches
- Use
batchedon Python 3.12 and later. It is shorter, faster, and rejects badnvalues for you. - Use the
islicerecipe when you must support older versions, or when you want batches as lists instead of tuples (list(islice(iterator, n))). - Use list slicing only when you already hold a list and need random access.
- Use
pairwiseinstead when you want overlapping neighbours rather than disjoint groups.pairwise([1, 2, 3, 4])gives(1, 2), (2, 3), (3, 4), while batches of 2 give(1, 2), (3, 4).
Exercise
What does list(batched('ABC', 5)) return, and what does list(batched('', 5)) return?
Show answer
The first returns [('A', 'B', 'C')], one short batch, because the input has fewer than 5 items. The second returns [], because an empty input yields no batches at all.
Exercise
This helper is meant to split any iterable into batches of n, but it never stops. Why, and how do you fix it?
from itertools import islice
def chunks(iterable, n):
while batch := tuple(islice(iterable, n)):
yield batch
Show answer
If iterable is a list, every islice call starts again from the first item, so the batch is never empty and the loop runs forever. Fix it by creating one iterator first with iterator = iter(iterable) and passing iterator to islice. That iterator remembers its position between calls, so it eventually produces an empty batch and the loop ends.