progress

~/problems / Iterators & parsers / Iterators and generators

An iterator class that yields chunks

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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 of size, in order. The last chunk may be shorter; never yield an empty one.
  • size must be a positive integer, otherwise raise ValueError.
  • iter(chunks) returns itself; once exhausted, next() keeps raising StopIteration.
  • 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.

Topic: Iterators and generators. Resumable/serializable iterators, merging streams, lazy pipelines.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc