A for loop works on anything that follows the iterator protocol: __iter__ returns the iterator itself, and __next__ returns the next item or raises StopIteration. Write one by hand.
Implement class Chunks:
Chunks(iterable, size)wraps any iterable (even an infinite generator) and yields its items in lists ofsize, in order. The last chunk may be shorter; never yield an empty one.sizemust be a positive integer, otherwise raiseValueError.iter(chunks)returns itself; once exhausted,next()keeps raisingStopIteration.- Lazy: pull only the items the current chunk needs; never list the whole input.
list(Chunks([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
list(Chunks("abc", 5)) # [["a", "b", "c"]]
list(Chunks([], 3)) # []
import itertools
c = Chunks(itertools.count(), 3)
next(c) # [0, 1, 2]
next(c) # [3, 4, 5]
Use a class with __iter__ and __next__, not a generator function.
Show hint
keep iter(iterable) in an attribute; __next__ calls next() on it up to size times, stopping early when it runs dry. An empty chunk means you're done.