Skip to content
dreamcode
dreamcode
Map
Iterators
Lesson 49 of 77
+15 XP on finish
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; each next() hands out one item
  • next(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.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Give Evens a __next__ method so it hands out 0, 2, 4 and so on below limit. print(list(Evens(7))) should print [0, 2, 4, 6].

Press Run to check your work.