Iterable protocol
The iterable protocol is how Python decides that an object can be walked by for, unpacked, or passed to list(). An iterable implements __iter__ (or the older __getitem__ sequence protocol) and returns a fresh iterator.
Detailed Explanation
"Iterable" and "iterator" are related and not the same. An iterable is a source of iterators. A list is iterable: every for item in items calls items.__iter__() and gets a new cursor at the start. An iterator is the cursor: it is iterable too, but __iter__ returns itself and the position is shared.
The modern protocol is one method. __iter__ must return an iterator, an object with __next__. If __iter__ is missing, Python falls back to the old sequence protocol: __getitem__ with indexes 0, 1, 2, ... until IndexError. That fallback is why a class that only implements __getitem__ still works in a for loop. New code should implement __iter__.
Many builtins consume iterables: list, tuple, set, sum, min, max, sorted, any, all, zip, map. Unpacking first, *rest = rows iterates. in on a non-dict iterates unless __contains__ exists. If you implement __iter__, you get all of that for free.
collections.abc.Iterable is the abstract class that checks for __iter__. Iterator also requires __next__. isinstance(obj, Iterable) is usually right and is wrong for the old __getitem__ iterables. iter(obj) is the runtime test: it succeeds or raises TypeError.
A container should return a new iterator each time. Returning self from a collection's __iter__ makes the collection one-shot, which breaks a second loop and surprises every caller. Generators are already iterators; a generator function is a factory for them, which is why for x in gen_func(): can run twice if you call gen_func() twice.
Infinite iterables are legal. itertools.count() never raises StopIteration on its own. Passing one to list() or sum() without a bound never returns. The protocol does not require a length. len is a separate method.
Code Examples
class Countdown:
def __init__(self, start: int):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n # a generator is a valid iterator
n -= 1
clock = Countdown(3)
print(list(clock)) # [3, 2, 1]
print(list(clock)) # [3, 2, 1] <- new iterator each timefrom collections.abc import Iterable, Iterator
print(isinstance([1, 2], Iterable)) # True
print(isinstance([1, 2], Iterator)) # False
print(isinstance(iter([1, 2]), Iterator)) # True
# Runtime check used by `for`:
iter("abc") # succeeds
# iter(3) # TypeError: 'int' object is not iterable# Unpacking and many builtins use the same protocol.
first, *rest = Countdown(4)
print(first, rest) # 4 [3, 2, 1]
print(sum(Countdown(3))) # 6Common Gotchas
Returning `self` from a collection `__iter__` makes it one-shot
the second `for` is empty. Yield from a generator or return a dedicated iterator object.
`isinstance(x, Iterable)` misses `__getitem__` iterables
call `iter(x)` if you must accept old sequence objects.
`list(infinite)` never finishes
`itertools.count`, unbounded generators, and network streams need an explicit stop.
Strings are iterable by character
`for ch in "ada"` walks letters. Wrap the string in a one-element list if you meant the whole string to be one item.