An iterator is an object that produces items one at a time. It's the protocol underlying every for loop — understanding it demystifies how iteration works and lets you make your own objects iterable.
The iterator protocol
iter(obj) gets an iterator; next(it) pulls the next value; when exhausted it raises StopIteration. A for loop does exactly this for you:
it = iter([10, 20, 30])next(it) # 10next(it) # 20next(it) # 30next(it) # raises StopIteration# for x in xs: ≈ it = iter(xs); repeatedly next(it) until StopIteration
Iterable vs iterator
An iterable is anything you can loop over (a list, a string); it provides __iter__. An iterator is the object doing the producing; it provides __next__. Calling iter() on an iterable gives you its iterator.
Making your own
class Countdown:def __init__(self, n):self.n = ndef __iter__(self):return self # I am my own iteratordef __next__(self):if self.n <= 0:raise StopIteration # signals "done"self.n -= 1return self.n + 1for x in Countdown(3):print(x) # 3, 2, 1
Key takeaways
- 01An iterator produces items one at a time via next(), raising StopIteration when done.
- 02A for loop calls iter() then next() repeatedly until StopIteration.
- 03An iterable provides __iter__; an iterator provides __next__.
- 04__iter__ + __next__ define a custom iterator.
- 05Iterators are lazy and often single-use — generators are the easy way to make them.
