Chunk any iterable, lazily in Python

Python interview exercise on Iterators & Generators, difficulty 2 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Write chunked(iterable, size), a generator that yields lists of up to size items. It must work for any iterable, including a generator or an endless one, so it cannot call len() or slice. Python 3.12 added itertools.batched for this; write it yourself here.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Iterators & Generators in Python

All Python exercises · Other languages and frameworks