Lesson 34 / 47

The Iterator Protocol

What actually happens when a `for` loop asks "what's next?"

Iterable vs iterator

An iterable has __iter__ (returns an iterator). An iterator has __next__ (returns the next value, or raises StopIteration).

Manually driving an iterator

for x in seq: is really: get an iterator, keep calling next(), stop on StopIteration. You can drive it manually too.

nums = [10, 20, 30]
it = iter(nums)
print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
# next(it)        # StopIteration