def batches(iterable, n): if not isinstance(iterable, list): iterable = list(iterable) if not iterable: return [] i = 0 while i < len(iterable): yield iterable[i:i+n] i += n