Skip to content

Commit 3652b26

Browse files
miss-islingtonrhettinger
authored andcommitted
Misc updates to the itertools recipes and tests (GH-98018)
(cherry picked from commit e500cc0) Co-authored-by: Raymond Hettinger <[email protected]>
1 parent a8a33e1 commit 3652b26

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

Doc/library/itertools.rst

+38-4
Original file line numberDiff line numberDiff line change
@@ -775,10 +775,7 @@ which incur interpreter overhead.
775775
return sum(map(pred, iterable))
776776

777777
def pad_none(iterable):
778-
"""Returns the sequence elements and then returns None indefinitely.
779-
780-
Useful for emulating the behavior of the built-in map() function.
781-
"""
778+
"Returns the sequence elements and then returns None indefinitely."
782779
return chain(iterable, repeat(None))
783780

784781
def ncycles(iterable, n):
@@ -860,6 +857,13 @@ which incur interpreter overhead.
860857
else:
861858
raise ValueError('Expected fill, strict, or ignore')
862859
860+
def batched(iterable, n):
861+
"Batch data into lists of length n. The last batch may be shorter."
862+
# batched('ABCDEFG', 3) --> ABC DEF G
863+
it = iter(iterable)
864+
while (batch := list(islice(it, n))):
865+
yield batch
866+
863867
def triplewise(iterable):
864868
"Return overlapping triplets from an iterable"
865869
# triplewise('ABCDEFG') -> ABC BCD CDE DEF EFG
@@ -1232,6 +1236,36 @@ which incur interpreter overhead.
12321236
>>> list(grouper('abcdefg', n=3, incomplete='ignore'))
12331237
[('a', 'b', 'c'), ('d', 'e', 'f')]
12341238

1239+
>>> list(batched('ABCDEFG', 3))
1240+
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
1241+
>>> list(batched('ABCDEF', 3))
1242+
[['A', 'B', 'C'], ['D', 'E', 'F']]
1243+
>>> list(batched('ABCDE', 3))
1244+
[['A', 'B', 'C'], ['D', 'E']]
1245+
>>> list(batched('ABCD', 3))
1246+
[['A', 'B', 'C'], ['D']]
1247+
>>> list(batched('ABC', 3))
1248+
[['A', 'B', 'C']]
1249+
>>> list(batched('AB', 3))
1250+
[['A', 'B']]
1251+
>>> list(batched('A', 3))
1252+
[['A']]
1253+
>>> list(batched('', 3))
1254+
[]
1255+
>>> list(batched('ABCDEFG', 2))
1256+
[['A', 'B'], ['C', 'D'], ['E', 'F'], ['G']]
1257+
>>> list(batched('ABCDEFG', 1))
1258+
[['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G']]
1259+
>>> list(batched('ABCDEFG', 0))
1260+
[]
1261+
>>> list(batched('ABCDEFG', -1))
1262+
Traceback (most recent call last):
1263+
...
1264+
ValueError: Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.
1265+
>>> s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1266+
>>> all(list(flatten(batched(s[:n], 5))) == list(s[:n]) for n in range(len(s)))
1267+
True
1268+
12351269
>>> list(triplewise('ABCDEFG'))
12361270
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
12371271

0 commit comments

Comments
 (0)