Group an iterable into tuples of a fixed maximum size.
What You Will Learn
batched(iterable, n, *, strict=False) emits tuples with at most n elements. The final tuple may be shorter unless strict=True, in which case an incomplete batch raises ValueError.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from itertools import batched
print(list(batched(range(7), 3)))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: itertools.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression list(batched(range(7), 3)) prints [(0, 1, 2), (3, 4, 5), (6,)]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[(0, 1, 2), (3, 4, 5), (6,)]
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from itertools import batched
print(list(batched(range(5), 2)))
Expected output:
[(0, 1), (2, 3), (4,)]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Divide 11 job IDs into groups of four.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming the final batch is always full without specifying strict=True.
- Overlooking this documented constraint: the final tuple may be shorter unless strict=True, in which case an incomplete batch raises ValueError.
Key Takeaways
- Group an iterable into tuples of a fixed maximum size.
- batched(iterable, n, *, strict=False) emits tuples with at most n elements.
- Apply this operation only after checking the assumptions and input conditions shown in the example.