Sub topic 1
Python Iterators and Generators: Lazy Sequences from First Principles
Prerequisites
You should know basic Python functions, classes, loops, collections, exceptions, and special methods such as __iter__.
Iterables and iterators: what is the difference?
An iterable is an object that can produce its items one at a time. Lists, tuples, strings, dictionaries, and sets are iterable. Calling iter() on an iterable creates an iterator.
An iterator remembers its current position. Calling next() asks for the next item. An iterator is usually single-use: after it reaches the end, it is exhausted.
flowchart LR
A[Iterable: list] -->|iter| B[Iterator]
B -->|next| C[Next value]
B -->|next repeatedly| D[StopIteration]The iterator protocol: __iter__, __next__ and StopIteration
The iterator protocol is the convention Python uses for iteration:
__iter__()returns an iterator.__next__()returns the next value.StopIterationsignals that no values remain.
numbers = [10, 20]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("exhausted")What a for loop really does
A for loop calls iter() once, then repeatedly calls next(). It catches StopIteration and ends the loop.
Conceptually, this:
for item in numbers:
print(item)behaves like this:
it = iter(numbers)
while True:
try:
item = next(it)
except StopIteration:
break
print(item)Building an iterator class by hand
A class can implement both protocol methods. Here, the object returns itself from __iter__() and stores its position in current.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]This class is both an iterable and its own iterator. Generators provide a shorter way to write the same protocol, which the next chapter develops.
Exercise
What does list(iter([1, 2])) produce, and why?
Show answer
It produces [1, 2]. iter([1, 2]) creates an iterator, and list() consumes that iterator.