Iterators and generators
More Python10 min readLesson 2 of 7
2.1 Iteration is a protocol
for does not know about lists specifically. It asks an object for an iterator with iter(), then calls next() until StopIteration is raised. Lists, dictionaries, files and range objects all follow this protocol, which is why one loop syntax works everywhere.
A generator function uses yield. Calling it returns a generator object that runs only as you request values. Local state stays alive between yields, which makes generators a natural way to describe a sequence without storing it.
def countdown(start):
while start > 0:
yield start
start -= 1
for value in countdown(3):
print(value)Output
3 2 1
Use a generator when each value depends on the previous one, when the source is a file or network stream, or when a helper would otherwise build a big intermediate list. A generator can be consumed only once.
