from itertools import islice | |
def batched(iterable, n, *, strict=False): | |
# batched('ABCDEFG', 3) → ABC DEF G | |
if n < 1: | |
raise ValueError('n must be at least one') | |
iterator = iter(iterable) | |
while batch := tuple(islice(iterator, n)): | |
if strict and len(batch) != n: | |
raise ValueError('batched(): incomplete batch') | |
yield batch |