Python · Generators & Iterators

What is an iterator?

Easyiteratoriterableprotocolnext

Interview question

What is an iterator in Python?

How to answer

The short answer

An iterable can produce an iterator (iter(obj)). An iterator is the object that walks values one at a time via next().

Protocol:

  • Iterable: defines __iter__() returning an iterator.
  • Iterator: defines __iter__() (returns self) and __next__() (returns next item or raises StopIteration).

Lists, dicts, files, and ranges are iterable. Calling iter(list) gives a separate iterator object. are iterators.

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

# Custom iterator
class CountUp:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

print(list(CountUp(3)))  # [0, 1, 2]

Interview framing: "Iterable = can be looped; iterator = the cursor that yields the next item."

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill