Python exercise · about 5 minutes · free
Iterator: Walk Through Data Without Loading It All
A file with a billion rows does not fit in memory. Hand out the rows in batches, one at a time.
The Iterator pattern gives sequential access to a collection without exposing how it is stored. In Python an iterator implements __iter__ and __next__ (raising StopIteration at the end); generators are the short way. Iterators are lazy: they produce values on demand, so they work on streams and huge files.
Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.
Your quest: Write the class
Batcher(iterable, size) that, when iterated, yields lists of up to size items (the last batch may be shorter). It must work on any iterable, including an endless one.Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
Hint
In <code>__init__</code> store <code>iter(iterable)</code> and the size; <code>__iter__</code> returns <code>self</code>; <code>__next__</code> collects up to <code>size</code> items with <code>next(it, sentinel)</code> and raises <code>StopIteration</code> if the batch is empty.Output appears here.