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
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.