LearnPy Hub
IntermediateAdvancedLesson 20 of 32

Iterators & Generators

Watch the ideaA generator pauses at yield
def count_up(n):
    i = 1
    while i <= n:
        yield i
        i += 1

g = count_up(3)
Variables
ggenerator (paused)

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: for uses iter() and next() behind the scenes; yield makes 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.

Step-by-step

Try it yourselfExample 1: iter() and next() by hand

This is what a for loop does for you.

example_1.py
Output appears here
Fill in the blanks

Step by step

Fill the blanks to get an iterator from the list and take the first two items: a b.

blanks.py
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.

example_2.py
Output appears here
Fill in the blanks

A generator of squares

Fill the blank so the generator gives the squares of 1 to 4 and the program prints [1, 4, 9, 16].

blanks.py
def squares(n):
    for i in range(1, n + 1):
         i * i

print(list(squares(4)))
Fix the bug

Return stops too soon

This generator should give every even number below 10: [0, 2, 4, 6, 8]. It only gives one. Fix it.

buggy.py

Example 3: An endless generator

Fibonacci numbers forever; islice takes just the first 12.

example_3.py
Output appears here
Your turn

Fibonacci 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].

my_code.py

Example 4: Memory saving and zip

The generator expression adds a million squares without ever storing a big list.

example_4.py
Output appears here
Your turn

Pair them up

Use zip to pair names = ["Mim", "Joy"] with marks = [88, 95] and print each pair as Mim: 88 then Joy: 95.

my_code.py

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.

Step-by-step

Example 5: A lazy processing pipeline

Nothing is computed until the final loop asks for items.

example_5.py
Output appears here

Example 6: itertools on endless streams

count() never ends, but islice and takewhile take just what's needed.

example_6.py
Output appears here

3Level 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.

example_7.py
Output appears here

Example 8: A running average with send()

Each send() delivers a number and gets back the average so far.

example_8.py
Output appears here
GotchaA generator can be used only once. After you've looped through it, it's empty: g = (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.
Exercise · predict the output

What does this print?

def gen():
    yield 1
    yield 2
    yield 3
g = gen()
next(g)
print(sum(g))
Quick quiz · 5 questions
1. What keyword turns a function into a generator?
2. What exception tells a loop that an iterator has run out?
3. What is the main advantage of a generator over a list?
4. What does list(zip([1, 2], ["a", "b"])) give?
5. What happens when you loop over the same generator a second time?
Ready to practice iterators & generators?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Iterators & Generators · LearnPy Hub