Skip to content

[3.11] Sync the batched() recipe with the 3.12 implementation #98446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,8 @@ which incur interpreter overhead.
def batched(iterable, n):
"Batch data into lists of length n. The last batch may be shorter."
# batched('ABCDEFG', 3) --> ABC DEF G
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while (batch := list(islice(it, n))):
yield batch
Expand Down Expand Up @@ -1272,12 +1274,6 @@ which incur interpreter overhead.
[['A', 'B'], ['C', 'D'], ['E', 'F'], ['G']]
>>> list(batched('ABCDEFG', 1))
[['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G']]
>>> list(batched('ABCDEFG', 0))
[]
>>> list(batched('ABCDEFG', -1))
Traceback (most recent call last):
...
ValueError: Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.
>>> s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> all(list(flatten(batched(s[:n], 5))) == list(s[:n]) for n in range(len(s)))
True
Expand Down