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 raisesStopIteration).
Lists, dicts, files, and ranges are iterable. Calling iter(list) gives a separate iterator object. Generators are iterators.
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."