runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Iterator class vs generator function

Produce the dates of a reporting week, one at a time.

what differs

Both follow the iterator protocol (__iter__ and __next__, ending with StopIteration). A generator function pauses at each yield and resumes where it left off, so its local variables are its state.

at a glance

approachuse it when
A · class with __next__The iterator needs extra methods or state that outside code inspects.
B · generator functionAlmost always: yield writes the iterator protocol for you.

Watch out: Both are single-use: after one pass they're exhausted. Make the class's __iter__ return a fresh iterator if it should be re-iterable.

the outputs

Each approach runs on the same input.

concepts

iterator protocolyieldStopIteration

learn it

Iterators: iter(), next() and StopIteration · Generator functions: yield one value at a time

related comparisons

List vs generator: using it twice · Recursion vs iteration

A · class with __next__
B · generator function
Compare Python Approaches · Runtime