Iterators & Generators
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
g = count_up(3)Calling a generator function doesn't run its body yet. You get a paused generator.
1Level 1 · BasicsBasics
A for loop works on lists, strings, dictionaries, files and ranges. How? They're all iterables. This lesson shows what's going on under the hood, and how generators let you produce values one at a time, which saves memory and lets you work with endless streams of data.
Iterables and iterators
An iterable is anything you can loop over. Calling iter() on it gives an iterator, an object that hands out one item each time you call next(). When it runs out, it raises StopIteration.
it = iter([10, 20]) next(it) # 10 next(it) # 20 next(it) # StopIteration
A for loop does exactly this for you and stops quietly at StopIteration.
Generators: functions that yield
A generator function uses yield instead of return. Each yield hands out one value and pauses the function. The next request resumes it right where it stopped.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for x in count_up_to(3):
print(x) # 1, 2, 3
Why generators?
- Memory: a list of a million numbers stores all million at once. A generator makes each number only when it's needed.
- Infinite sequences: a generator can go on forever, and you take only what you need.
- Pipelines: chain small generators, e.g. read lines, then keep the interesting ones, then convert them, without building big lists in between.
Generator expressions
Like a list comprehension but with round brackets: (n * n for n in range(10)). Pass one straight into sum(), max() or any().
Helpful built-ins
enumerate(), zip(), range(), map() and filter() are all lazy iterators. zip(a, b) pairs items from two lists, and itertools adds tools like islice (take the first n items) and count.
Key points:forusesiter()andnext()behind the scenes;yieldmakes a generator that pauses and resumes; generators save memory and can be infinite; a generator can be used up only once.
See it in actionA generator pauses at yield
Each next() resumes count_up right after the yield where it stopped.
Try it yourselfExample 1: iter() and next() by hand
This is what a for loop does for you.
Output appears hereStep by step
Fill the blanks to get an iterator from the list and take the first two items: a b.
letters = ["a", "b", "c"] it = (letters) print((it), next(it))
Example 2: A generator function
The prints show the function pausing at each yield and resuming later.
Output appears hereA generator of squares
Fill the blank so the generator gives the squares of 1 to 4 and the program prints [1, 4, 9, 16].
def squares(n): for i in range(1, n + 1): i * i print(list(squares(4)))
Return stops too soon
This generator should give every even number below 10: [0, 2, 4, 6, 8]. It only gives one. Fix it.
Example 3: An endless generator
Fibonacci numbers forever; islice takes just the first 12.
Output appears hereFibonacci generator
Write a generator fib() that yields 0, 1, 1, 2, 3, 5, … for ever. Print the first 8 numbers as a list: [0, 1, 1, 2, 3, 5, 8, 13].
Example 4: Memory saving and zip
The generator expression adds a million squares without ever storing a big list.
Output appears herePair them up
Use zip to pair names = ["Mim", "Joy"] with marks = [88, 95] and print each pair as Mim: 88 then Joy: 95.
2Level 2 · IntermediatePipelines and itertools
Generator pipelines
Chain generators like an assembly line: read lines → clean them → filter → convert. Each item flows through the whole line before the next one starts, so memory stays tiny even for huge data.
yield from
yield from other() hands out every item of another generator, which is handy for recursion (walking a tree of folders).
itertools for iterators
islice takes the first n items of an endless generator; count, cycle and repeat make endless streams; chain joins several; groupby groups neighbours with the same key; takewhile stops when a condition fails.
See it in actionA generator pauses and resumes
Watch the arrow jump back into the generator at each next(), right after the last yield.
Example 5: A lazy processing pipeline
Nothing is computed until the final loop asks for items.
Output appears hereExample 6: itertools on endless streams
count() never ends, but islice and takewhile take just what's needed.
Output appears here3Level 3 · AdvancedThe iterator protocol and generator superpowers
Writing your own iterator class
An iterable has __iter__, which returns an iterator; an iterator has __next__, which returns the next item or raises StopIteration. Every for loop uses this protocol.
Iterators are used up
Once an iterator (or generator) is exhausted, looping again gives nothing. If you need several passes, keep the iterable (a list, or a class whose __iter__ makes a fresh iterator).
send() and return values
A generator can receive values: value = yield result. That makes "coroutines" that keep state between calls, such as a running average. return x inside a generator becomes the value of yield from.
Example 7: A countdown class and a used-up generator
The class can be looped many times; the generator only once.
Output appears hereExample 8: A running average with send()
Each send() delivers a number and gets back the average so far.
Output appears hereg = (x for x in range(3)); list(g) gives [0, 1, 2], but a second list(g) gives []. Turn it into a list if you need it twice.What does this print?
def gen():
yield 1
yield 2
yield 3
g = gen()
next(g)
print(sum(g))50 graded problems are waiting in Topic Practice.