"""Tools for iterables which are not presented in core libs.""" import itertools def batched(iterable, n): """Batch data into lists of length *n*. The last batch may be shorter. >>> list(batched('ABCDEFG', 3)) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)] On Python 3.12 and above, replace it with standard :func:`itertools.batched`. """ if n < 1: raise ValueError('n must be at least one') it = iter(iterable) while True: batch = list(itertools.islice(it, n)) if not batch: break yield batch