Iterators
An iterator is an object that produces values one at a time and remembers its place. You get the next value with next(it), and when the values run out it raises StopIteration.
Detailed Explanation
A for loop does not index. It asks the iterable for an iterator, then calls next until StopIteration. The iterator is the cursor. The iterable is the collection (or generator function) that can produce a cursor.
An iterator implements __next__ and __iter__. __next__ returns the next item or raises StopIteration. __iter__ returns self, so an iterator is iterable and for works on it directly. After it is exhausted, further next calls keep raising StopIteration. There is no rewind. To walk the data again you need a new iterator from the original iterable.
iter(obj) calls obj.__iter__() and returns the iterator. iter(func, sentinel) is the two-argument form: it calls func() until the return value equals sentinel. That is the usual way to read a file in blocks: iter(lambda: file.read(4096), b"").
next(it, default) returns default instead of raising at the end. next((x for x in items if pred(x)), None) is a common "first match or None" without a flag.
Iterators are lazy. A generator function is the easiest way to write one: each yield produces a value and pauses. map, zip, filter, file objects, and dict views are iterators or produce them. Turning an iterator into a list with list(it) forces every remaining value into memory and spends the iterator.
You cannot copy the position by assignment. b = a shares the same cursor. itertools.tee can split an iterator into two, at the cost of buffering values that one side has not consumed yet. If you need to walk twice, materialise a list or iterate the original collection twice.
Custom iterators belong in a class when the state is more than a generator can hold cleanly, such as a tree walk with an explicit stack. For everything else, write a generator function.
Code Examples
skus = ["A-1", "B-2", "C-3"]
cursor = iter(skus)
print(next(cursor)) # A-1
print(next(cursor)) # B-2
print(next(cursor)) # C-3
print(next(cursor, None)) # None, instead of StopIterationdef countdown(n: int):
while n > 0:
yield n
n -= 1
ticks = countdown(3)
print(list(ticks)) # [3, 2, 1]
print(list(ticks)) # [] <- exhausted# Two names, one cursor.
it = iter([10, 20, 30])
alias = it
print(next(it), next(alias)) # 10 20Common Gotchas
An iterator is one-shot
a second `for` over the same generator is empty. Keep the list or recreate the generator.
`iter(a)` on an iterator returns the same object
`list(it)` then `list(it)` does not walk twice. Call `iter(original)` again.
Sharing an iterator shares the position
passing the same generator to two functions means each sees leftover items.
`StopIteration` in a generator becomes `RuntimeError`
do not raise `StopIteration` by hand inside a generator. `return` ends it.