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
| approach | use it when |
|---|---|
| A · class with __next__ | The iterator needs extra methods or state that outside code inspects. |
| B · generator function | Almost 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