Iterators and generators
Every for loop in Python uses the iterator protocol. Understanding it unlocks generators: functions that produce values one at a time, using almost no memory, even for millions of items or endless streams.
How a for loop really works
An iterable is anything you can loop over (lists, strings, dicts, files…). iter() gets an iterator from it, and next() asks the iterator for the next value until it raises StopIteration:
A for loop does exactly this, and stops quietly at StopIteration.
Generators: functions that yield
A function containing yield is a generator function. Calling it doesn't run the body. It returns a generator that runs step by step, pausing at each yield:
Why generators matter: laziness
A list holds every value in memory at once. A generator produces each value only when asked:
That makes generators ideal for large files, database results, and data pipelines.
Infinite sequences
Since values are produced on demand, a generator can go on forever, and you take as many as you need:
Building pipelines
Chain generators together; each item flows through every step before the next one starts. Here's a log analyser that would work just as well on a 10 GB file:
yield from
yield from hands over to another iterable, which is handy for recursion:
Making your own iterable class
Give a class an __iter__ method (it can simply be a generator):
Tools that work with any iterable
A generator can only be used once
If you need the values again, make a new generator or store them in a list.
Practice
- Write a generator
evens(limit)that yields even numbers up tolimit. - Write a generator
read_numbers(lines)that skips blank lines and lines starting with#, and yields the remaining lines as ints. Sum the result. - Using
itertools.isliceand your own generator, print the first 10 prime numbers.
1.What happens when you call a generator function?
2.What's the difference between [x*x for x in data] and (x*x for x in data)?
3.What does list(gen) return the second time on the same generator?