Stop 08 · Intermediate PythonTopics · 1/10

Iterators & the Iterator Protocol

Part of the Python Roadmap

In short

for loops work on lists, strings, dicts, files and even database cursors. The reason is one tiny agreement called the iterator protocol, and once you see it, a lot of Python suddenly makes sense.

An iterable is anything you can loop over, and an iterator produces its items one at a time through __next__() until it raises StopIteration. for loops call iter() and next() for you behind the scenes.

The jaadu presses the big button on a bank token machine as a single paper slip curls out of the slot.

Think of it like this

The token machine at the bank

The bank's token machine gives out one numbered slip each time you press the button: 1, 2, 3. It doesn't print all hundred tokens in the morning. When the day's tokens run out, it shows 'closed'. An iterator is that machine: next() gives the next item, and StopIteration means 'closed'.

Watch it happen

What a for loop over ['UPI', 'Card', 'Cash'] really does

UPI
0
Card
1
Cash
2

1/5for calls iter(methods) once to get an iterator that remembers its position.

The big ideas

What you need to know

Iterable vs iterator

An iterable (list, str, dict) can give you an iterator with iter(). The iterator does the actual stepping with next().

Two methods

An iterator has __iter__ (returning itself) and __next__ (returning the next item or raising StopIteration).

One-time use

An iterator is used up after one pass. Call iter() on the original iterable again to restart.

Lazy

Iterators produce items on demand, so files, range() and zip() never need all their items in memory at once.

See it in code

Walk through the code

python
1methods = ["UPI", "Card", "Cash"]2it = iter(methods)3print(next(it))     # UPI4print(next(it))     # Card5print(next(it))     # Cash6# next(it) now raises StopIteration7 8class Countdown:9    def __init__(self, start: int):10        self.current = start11 12    def __iter__(self):13        return self14 15    def __next__(self) -> int:16        if self.current <= 0:17            raise StopIteration18        value = self.current19        self.current -= 120        return value21 22for n in Countdown(3):23    print(n)        # 3, 2, 124 25nums = iter([1, 2, 3])26print(sum(nums))    # 627print(sum(nums))    # 0, already used up

1/6iter() gives an iterator and each next() returns one item. After the last one, StopIteration.

Stepping through a list by hand, a custom Countdown iterator, and proof that iterators are one-time use.

Save yourself the pain

Common mistakes

Oops

Looping over the same iterator (like a zip or map object) twice and getting nothing the second time.

Do this instead

Convert it to a list if you need it more than once, or recreate it.

Oops

Returning None at the end of __next__ instead of raising StopIteration.

Do this instead

Returning None makes the loop run forever. Raise StopIteration to signal the end.

Your mission

Odd number iterator

~20 min

Quick check

What signals the end of an iterator in Python?

Go deeper

  1. 1Call iter() and next() by hand on a list to see how a for loop works.
  2. 2Write a small class with __iter__ and __next__ that counts down.
  3. 3Notice that an iterator is used up after one full pass.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge