← All lessons
Python advanced · Lesson 5 of 11

Iterators and generators

Anything a for loop can go through is iterable: lists, strings, dicts, files, ranges. Behind the scenes the loop calls iter() on it to get an iterator, an object that hands out one item each time next() is called and raises StopIteration when it runs out. The loop catches that and stops.

it = iter(["a", "b"])
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print("done")
Prints
a
b
done

The easiest way to make your own iterator is a generator function: a function that uses yield instead of return. Calling it doesn't run the body; it gives back a generator. Each next() runs the body until the next yield, hands out that value, and pauses there, keeping all its local variables, until it's asked again.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)
print(list(countdown(4)))
Prints
3
2
1
[4, 3, 2, 1]

Generators are lazy: they make each value only when asked. That means they can work through data far bigger than memory (a 50 GB log file, line by line) and even go on forever, as long as whoever reads them stops.

def evens():
    n = 0
    while True:
        yield n
        n += 2

for e in evens():
    if e > 6:
        break
    print(e)
Prints
0
2
4
6

A generator expression is a comprehension with round brackets. It doesn't build a list; it makes values one at a time. Passed straight to a function like sum(), it needs no extra brackets. One catch: a generator can only be gone through once.

total = sum(n * n for n in range(1_000_000))
print(total)
gen = (c.upper() for c in "ab")
print(list(gen), list(gen))
Prints
333332833333500000
['A', 'B'] []

(Underscores in a number like 1_000_000 are only there to make it readable.) The itertools module is a toolbox of iterator building blocks: islice takes the first n items of any iterator, count counts forever, chain joins iterables end to end, groupby groups runs of equal items, and combinations and permutations do what they say. yield from other hands out every item of another iterable from inside a generator.

from itertools import islice, chain, combinations, count

print(list(islice(count(10, 5), 3)))
print(list(chain([1, 2], "ab")))
print(list(combinations("xyz", 2)))
Prints
[10, 15, 20]
[1, 2, 'a', 'b']
[('x', 'y'), ('x', 'z'), ('y', 'z')]

Practice

What does this print?

def squares(n):
    for i in range(n):
        yield i * i

print(list(squares(4)))
More info

Quick reference

iterable / iteratorSomething you can loop over / the object that hands out items with next().
yieldHand out a value and pause; makes the function a generator.
(expr for x in xs)A generator expression: lazy, one pass only.
yield from itYield every item of another iterable.
itertoolsislice, count, chain, groupby, combinations, permutations and more.

Related courses