Skip to main content
Albero Academy

Iterators

The protocol behind every for loop — iter() and next().

Advanced Python9 min

An iterator is an object that produces items one at a time. It's the protocol underlying every for loop — understanding it demystifies how iteration works and lets you make your own objects iterable.

The iterator protocol

iter(obj) gets an iterator; next(it) pulls the next value; when exhausted it raises StopIteration. A for loop does exactly this for you:

what a for loop really does
it = iter([10, 20, 30])
next(it) # 10
next(it) # 20
next(it) # 30
next(it) # raises StopIteration
# for x in xs: ≈ it = iter(xs); repeatedly next(it) until StopIteration

Iterable vs iterator

An iterable is anything you can loop over (a list, a string); it provides __iter__. An iterator is the object doing the producing; it provides __next__. Calling iter() on an iterable gives you its iterator.

Making your own

a custom iterator
class Countdown:
def __init__(self, n):
self.n = n
def __iter__(self):
return self # I am my own iterator
def __next__(self):
if self.n <= 0:
raise StopIteration # signals "done"
self.n -= 1
return self.n + 1
for x in Countdown(3):
print(x) # 3, 2, 1

Key takeaways

  1. 01An iterator produces items one at a time via next(), raising StopIteration when done.
  2. 02A for loop calls iter() then next() repeatedly until StopIteration.
  3. 03An iterable provides __iter__; an iterator provides __next__.
  4. 04__iter__ + __next__ define a custom iterator.
  5. 05Iterators are lazy and often single-use — generators are the easy way to make them.

Finished this chapter?

Mark it complete to track your progress through Python.