Topics / 🏗️ Design Patterns (GoF) / 🔭 Level 87: Design Patterns: Behavioural II

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.

Flow: stream of items → next() x size (collect a batch) → yield [..] (lazy, memory stays small)stream of itemsnext() x sizecollect a batchyield [..]lazy, memory stays small
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.
HintIn <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.

Open it in the full course → Free with Google: saves your progress and unlocks 627 lessons.

In this level you'll learn:
More in Level 87: Design Patterns: Behavioural II

Share on LinkedIn