PYTHON ADVANCEDChapter 9 · Python Advanced
Iterators and the for loop
A for loop works on anything iterable. Under the hood it calls iter() to get an iterator, then calls next() on it again and again until the iterator raises StopIteration. Build your own iterator by giving a class __iter__ and __next__. Iterators are lazy: they hand out one value at a time instead of building a whole list.
Worked example
How it reads
iter(colors)gives an iterator; eachnext()hands out one itemnext(it, "done")returns the default instead of raising when it runs out__next__raising StopIteration is how a loop knows to stop

Cloud tip: An iterator can only be walked once. Call
list(...) if you need to loop over the values twice.

