Intermediate Python · Lesson 6 of 14

Iterators and generators

See how for loops really work with iter and next, write generator functions with yield, and process big data one item at a time.

About 18 minutes · code runs in your browser, nothing to install

Lists, strings, dictionaries and files can all be looped over: they are iterable. Behind every for loop is an iterator, an object that hands out one item at a time and remembers where it is. iter() gets an iterator from an iterable, and next() asks it for the next item.

Pythoneditable
colours = ["red", "green", "blue"]
it = iter(colours)
print(next(it))
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print("No more items")
Output
red
green
blue
No more items

When the items run out, next() raises StopIteration. A for loop catches it for you and simply stops.

Generator functions and yield

The easiest way to make your own iterator is a generator function: a normal function that uses yield (generators) instead of return. Each yield hands out one value and pauses the function. The next request resumes it right after the yield, with all its variables intact.

Pythoneditable
def countdown(start):
    while start > 0:
        yield start
        start -= 1
    yield "Lift off!"

for value in countdown(3):
    print(value)

print(list(countdown(2)))
Output
3
2
1
Lift off!
[2, 1, 'Lift off!']

Calling a generator function does not run its body yet; it returns a generator object. The code only runs when someone asks for values. The prints below show the order in which things happen.

Pythoneditable
def numbered(items):
    print("  (starting)")
    for i, item in enumerate(items, start=1):
        print(f"  (making item {i})")
        yield f"{i}. {item}"

gen = numbered(["tea", "rice"])
print("Generator created, nothing has run yet")
for line in gen:
    print(line)
Output
Generator created, nothing has run yet
  (starting)
  (making item 1)
1. tea
  (making item 2)
2. rice

Why generators: one item at a time

A list holds every item in memory at once. A generator makes each item only when it is needed, so it can work through a file with millions of lines, or even an endless stream, using very little memory.

Pythoneditable
def order_ids(first=1001):
    n = first
    while True:
        yield f"ORD-{n}"
        n += 1

ids = order_ids()
print(next(ids))
print(next(ids))
for customer, order in zip(["Ana", "Ben", "Chen"], ids):
    print(customer, order)
Output
ORD-1001
ORD-1002
Ana ORD-1003
Ben ORD-1004
Chen ORD-1005

order_ids() never ends on its own. zip() stops at the shortest input, so only three more ids are made.

Generator expressions

A generator expression looks like a list comprehension with round brackets. It is ideal inside sum(), max(), any() and all(), which only need to see each value once.

Pythoneditable
prices = [12.5, 3.0, 7.25, 20.0]
print(sum(p * 2 for p in prices))
print(max(len(w) for w in ["kiwi", "banana", "fig"]))
print(any(p > 15 for p in prices))

squares = (n * n for n in range(4))
print(list(squares))
print(list(squares))
Output
85.5
6
True
[0, 1, 4, 9]
[]

A generator can be used only once: the second list() finds it already empty.

A small pipeline

Generators chain nicely: each step takes items from the previous one. Here a file of orders is read, cleaned and added up without ever building a full list.

Pythoneditable
def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.strip()

def amounts(lines):
    for line in lines:
        if line and not line.startswith("#"):
            name, amount = line.split(",")
            yield float(amount)

total = sum(amounts(read_lines("orders.txt")))
print(f"Total: {total:.2f}")
Output
Total: 49.75

✎ Exercise

Write a generator even_squares(limit) that yields the square of every even number from 0 up to and including limit.

Hint: Loop with range(0, limit + 1, 2) and yield n * n inside the loop.

Your codewrite your answer, then Run
def even_squares(limit):
    # your code here
    pass

print(list(even_squares(10)))
print(sum(even_squares(6)))

Expected output:

[0, 4, 16, 36, 64, 100]
56
Show a solution
Solutioneditable
def even_squares(limit):
    for n in range(0, limit + 1, 2):
        yield n * n

print(list(even_squares(10)))
print(sum(even_squares(6)))
Output
[0, 4, 16, 36, 64, 100]
56

Check yourself

1. What happens when you call a generator function?

2. What does next() raise when an iterator has no more items?

3. Which line creates a generator expression?

Spotted a mistake on this page? Tell us