
Everything you loop over in Python implements the iterator protocol.
Iterator protocol:
An object is iterable if it has __iter__(). An iterator also has __next__().
my_list = [1, 2, 3] iterator = iter(my_list) next(iterator) # 1 next(iterator) # 2 next(iterator) # 3 next(iterator) # raises StopIteration
Custom iterator:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
for n in Countdown(3):
print(n) # 3, 2, 1Why this matters: Understanding iterators explains how for loops work, why generators are memory-efficient, and how to make your own objects loopable.
Reference:
TaskLoco™ — The Sticky Note GOAT