Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleVery commonTheory

What is the iterator protocol, and how does it relate to the difference between an iterable and an iterator?

Answer

An iterable is any object for which `iter(obj)` can produce an iterator — most commonly because it implements `__iter__`, which returns an iterator, but Python's iteration protocol also recognizes the older sequence protocol: an object with no `__iter__` but a working `__getitem__(self, index)` starting at index 0 is still iterable, since `iter()` falls back to calling it with increasing integer indices until `IndexError`. An iterator itself is any object that implements both `__iter__` (usually returning itself) and `__next__`, which returns the next value or raises `StopIteration` when exhausted. A `for` loop is essentially sugar for calling `iter(obj)` once to get an iterator, then calling `next()` on it repeatedly until `StopIteration` is caught. A list is iterable but is not itself an iterator — `iter([1, 2, 3])` produces a fresh, separate list-iterator object each time it is called.

Strong answer includes

  • iterable is anything iter() can get an iterator from — usually __iter__, or the legacy __getitem__ sequence protocol
  • iterator implements __iter__ and __next__, raises StopIteration when exhausted
  • a for loop is sugar for iter() then repeated next()

Practical example

What a for loop does internally
Python
editable · browser sandbox
Result
Run the code to see the result.

for obtains an iterator once with iter(), repeatedly calls next(), and stops when StopIteration is raised. Lists are iterable; the separate object returned by iter(list) is the iterator.

Expected result: 10 followed by 20.

#iterators#protocols

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics