Deviopath › Python

Reusable Pages Iterable

Hard · Iterators

An iterable is anything with __iter__. An iterator is the object that __iter__ returns: it remembers a position and is used up after one pass. If __iter__ returns a fresh iterator every time (a generator method is the easiest way), the object can be looped over many times, even in nested loops.

Write a class Pages(items, size) that splits items into pages:

- a size smaller than 1 raises ValueError("size must be at least 1")

- iterating yields lists of up to size items, in order

- len(pages) is the number of pages

- every loop starts from the first page, independently of other loops

The driver run_pages(items, size) is already written. It returns the page count, two full passes, and how many pairs a nested loop over the pages produces (count * count when the iterators are independent).

Next: Lazy Generator Pipeline