Python · The language, not just syntax

What is the iterator protocol?

Mediumiteratorsprotocolsfor loopsUpdated Oct 2026
Quiz this track

Short answer

An iterable implements __iter__ and returns an iterator. An iterator implements __next__ and raises StopIteration when exhausted. A for loop calls iter on the iterable and next until StopIteration.

The protocol is small and structural. Anything with __iter__ is iterable, and anything with __next__ is an iterator. Iterators usually also implement __iter__ by returning self, which is what makes them usable directly in for loops.

python
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

print(list(Countdown(3)))
The for loop calls iter, then next until StopIteration, and stops without surfacing the exception.

Iterable versus iterator

  • A list is iterable but not an iterator: it can produce a fresh iterator each time
  • A generator is both iterable and an iterator, and it is exhausted after one pass
  • iter(obj) calls obj.__iter__, and next(obj) calls obj.__next__
  • StopIteration signals exhaustion and is consumed by for loops

An iterator holds traversal state. If the object itself is the iterator, calling iter on it twice returns the same exhausted object. That is why a custom collection should normally return a separate iterator object rather than self.

A function that uses yield in its body is always a generator function. Remember to import from collections.abc when checking isinstance against Iterable or Iterator.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between an iterable and an iterator?
  2. 2Why does an iterator's __iter__ usually return self?
  3. 3What exception signals the end of iteration?
  4. 4How would you implement a class that supports multiple independent passes?

Say it in the interview

An iterable provides __iter__, and an iterator provides __next__ plus an __iter__ that usually returns self. The for loop calls iter once and next repeatedly until StopIteration. The distinction matters because a list can give you a fresh iterator each pass, while a generator is exhausted after one pass. For custom collections I return a separate iterator so multiple traversals stay independent.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.