Module 14 · Advanced · Advanced Python

Python generators and yield, with examples

Python generators and yield with examples: generator functions and expressions, reading big files lazily, pipelines, infinite sequences and yield from.

By theprogrammers team · · 10 min read

You need to go through a 4 GB file of UPI transactions and add up the amounts. Reading it into a list would need more memory than many laptops have. What you want is a function that hands you one transaction at a time, pauses, and carries on from the same place when you ask for the next. Python generators are exactly that: functions that use yield instead of return to give values one at a time.

Generators are the easy way to write the iterators from the previous lesson. A class with __iter__ and __next__ takes about ten lines; the same generator takes three. They're used everywhere big or endless data appears: reading files, streaming from APIs, and feeding data to machine learning models.

What you need first: Python iterators and iterables and Python functions.

Key terms

  • Generator function: a function that contains yield. Calling it doesn't run the body; it returns a generator.
  • Generator: the iterator a generator function returns. It runs the function's body bit by bit as you ask for values.
  • yield: like return, but the function pauses instead of ending, and resumes from that line next time.
  • Generator expression: a one-line generator in round brackets, like (n * n for n in range(10)).
  • Pipeline: several generators chained together, each taking values from the one before.

Your first generator

def token_machine(start, count):
    for token in range(start, start + count):
        yield token

machine = token_machine(101, 3)
print(machine)
print(next(machine))
print(next(machine))
print(list(machine))

The first line prints something like <generator object token_machine at 0x7f...>; the address at the end is different every run, so we don't show it. The rest prints:

101
102
[103]

Calling token_machine(101, 3) didn't run any of its code. It returned a generator. Each next() runs the body until the next yield, hands back that value and pauses. When the body ends, the generator raises StopIteration automatically, so it works in for loops, list(), sum() and everywhere else an iterator does.

How yield pauses and resumes

Print statements make the pausing visible:

def steps():
    print("  starting")
    yield 1
    print("  resumed after 1")
    yield 2
    print("  resumed after 2, finishing")

gen = steps()
print("Created the generator")
print("Got", next(gen))
print("Got", next(gen))
print("Got", next(gen, "nothing left"))
Created the generator
  starting
Got 1
  resumed after 1
Got 2
  resumed after 2, finishing
Got nothing left

Nothing ran until the first next(). Each next() ran only up to the following yield. Local variables keep their values while the generator is paused, which is what makes this so useful.

return vs yield

def squares_list(n):
    result = []
    for i in range(n):
        result.append(i * i)
    return result

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

print(squares_list(5))
print(list(squares_gen(5)))
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
Function with returnGenerator with yield
RunsEverything, at onceBit by bit, as values are requested
Gives backOne value (often a full list)Many values, one at a time
MemoryHolds all the resultsHolds one result at a time
Can be loopedMany times (it's a list)Once
Infinite sequencesImpossibleEasy

The generator version is shorter too: no empty list, no append, no return.

Generator expressions

For simple cases, a generator expression is a comprehension in round brackets:

prices = [120, 45, 380, 99]
with_gst = (round(p * 1.18, 2) for p in prices)
print(next(with_gst))
print(round(sum(with_gst), 2))
141.6
618.32

The sum is of the three prices left, because next already took the first. When a generator expression is the only argument to a function, you can drop the extra brackets: sum(p * 1.18 for p in prices).

Reading a big file lazily

This is the most common real use. Here we create a small sample file first; the same code works unchanged on a file of several gigabytes:

from pathlib import Path

Path("payments.csv").write_text(
    "id,amount,status\n1,250,success\n2,1200,failed\n3,99,success\n4,5000,success\n",
    encoding="utf-8",
)

def read_rows(path):
    with open(path, encoding="utf-8") as f:
        next(f)                          # skip the header line
        for line in f:
            id_, amount, status = line.strip().split(",")
            yield {"id": int(id_), "amount": int(amount), "status": status}

total = sum(row["amount"] for row in read_rows("payments.csv") if row["status"] == "success")
print(total)
5349

At no point is the whole file in memory: the file object hands out one line, the generator turns it into one dictionary, and sum adds it. Memory use stays the same whether the file has 4 rows or 4 crore.

Generator pipelines

Each generator can take another generator as its input, like stations on an assembly line. Each step is small, easy to test and lazy:

from pathlib import Path

Path("server.log").write_text(
    "INFO start\nERROR disk full\nINFO user login\nERROR timeout\nWARNING slow\n",
    encoding="utf-8",
)

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

def errors_only(rows):
    for row in rows:
        if row.startswith("ERROR"):
            yield row

def messages(rows):
    for row in rows:
        yield row.split(" ", 1)[1]

pipeline = messages(errors_only(lines("server.log")))
print(list(pipeline))
['disk full', 'timeout']

Nothing happens until list() starts pulling values. Then each line flows through all three steps before the next line is read.

Infinite generators

A generator doesn't have to end. This one gives Fibonacci numbers for ever, and the caller decides when to stop:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

for n in fibonacci():
    if n > 100:
        break
    print(n, end=" ")
0 1 1 2 3 5 8 13 21 34 55 89

while True is safe here because the generator pauses at every yield. Never call list() on an infinite generator, though: it will try to collect values for ever and use up your memory. Use break, or itertools.islice from the itertools lesson, to take just some.

yield from

When a generator wants to pass along every value from another iterable, yield from does it in one line:

def all_students(sections):
    for section in sections:
        yield from section

sections = [["Ahana", "Dev"], ["Meera"], ["Rohan", "Sara"]]
print(list(all_students(sections)))
['Ahana', 'Dev', 'Meera', 'Rohan', 'Sara']

yield from section is short for for name in section: yield name. It's particularly neat for recursive generators, such as flattening nested lists:

def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print(list(flatten([1, [2, [3, 4]], 5])))
[1, 2, 3, 4, 5]

Generators are used up after one pass

A generator is an iterator, so it can only be looped once:

evens = (n for n in range(10) if n % 2 == 0)
print(sum(evens))
print(sum(evens))
20
0

If you need the values twice, either call the generator function again to get a fresh generator, or store the values with list().

When to use a generator

Use a generator when:

  • The data is large and you only need one item at a time (files, database rows, API pages).
  • The sequence is endless or you don't know where it ends.
  • You're building a pipeline of small processing steps.
  • You might stop early, so working out every value in advance would be wasted.

Use a list when you need len(), indexing, sorting, or several passes over the same values. For a few hundred items, a list is simpler and the memory difference doesn't matter.

Where generators are used

  • Data engineering: reading and transforming files row by row, in pipelines like the one above.
  • Machine learning: Keras and PyTorch can take generators that produce training batches, so datasets bigger than memory can still be used.
  • Web frameworks: Flask and FastAPI can stream a big download or a live response from a generator.
  • Python itself: range, zip, map, enumerate, dict.items() and file reading are all lazy in the same spirit.

Common mistakes

  • Expecting a generator function to run when called. It only runs when you ask for values.
  • Looping over a generator twice. The second loop gets nothing.
  • Calling len() or indexing a generator. Convert it to a list first, if it's small.
  • list() on an infinite generator, which never finishes.
  • Using return value to send back the results: in a generator, return just ends it. The value isn't produced by the loop.

Practice

  1. Write a generator evens(limit) that yields even numbers from 0 up to limit, and print them for limit = 10.
Show the answer
def evens(limit):
    for n in range(0, limit + 1, 2):
        yield n

print(list(evens(10)))
[0, 2, 4, 6, 8, 10]
  1. What does this print?
def g():
    yield "a"
    yield "b"
    return
    yield "c"

print(list(g()))
Show the answer
['a', 'b']

return ends the generator, so yield "c" never runs.

  1. Write a generator expression that gives the lengths of the words in "generators save memory", and use it to find the longest length.
Show the answer
print(max(len(w) for w in "generators save memory".split()))
10
  1. Write an infinite generator multiples(n) that yields n, 2n, 3n, ..., and print the first 5 multiples of 7 using next().
Show the answer
def multiples(n):
    k = 1
    while True:
        yield n * k
        k += 1

m = multiples(7)
print([next(m) for _ in range(5)])
[7, 14, 21, 28, 35]
  1. Write a generator batches(items, size) that yields lists of size items at a time, with the last batch smaller if needed. Test it with range(1, 8) and size 3.
Show the answer

Collect items until the batch is full, yield it, start a new one, and yield any leftovers at the end:

def batches(items, size):
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch

print(list(batches(range(1, 8), 3)))
[[1, 2, 3], [4, 5, 6], [7]]

This is how training data is split into mini-batches. Python 3.12 added itertools.batched, which does the same job and yields tuples.

Interview questions

What is the difference between yield and return?

return sends back one value and ends the function, discarding its local state. yield sends back a value and pauses the function, keeping its local variables, so it can resume from the same point on the next next() call. A function containing yield becomes a generator function.

What is the difference between a list comprehension and a generator expression?

A list comprehension (square brackets) builds the whole list in memory immediately and can be reused. A generator expression (round brackets) produces values lazily, one at a time, uses almost no memory and can be iterated only once.

What does yield from do?

It delegates to another iterable or generator, yielding each of its values in turn. It replaces a for loop with yield inside it, and for sub-generators it also passes through values sent in and the sub-generator's return value.

Key takeaways

  • A function with yield returns a generator; its body runs only as values are requested.
  • yield pauses the function and keeps its local variables; next() resumes it.
  • Generators use memory for one value at a time, so they suit huge files and endless sequences.
  • Generator expressions are comprehensions in round brackets.
  • Chain generators into pipelines; use yield from to pass along another iterable.
  • A generator can be consumed only once.

Frequently asked questions

Are generators faster than lists?

Not necessarily for small data; building a list can even be slightly faster. Their big advantage is memory: they keep one value at a time, and they can stop early without computing the rest.

Can a generator have a return statement?

Yes. return ends the generator. A value given to return is attached to the StopIteration exception, and yield from can receive it, but a normal for loop ignores it.

How do I get the length of a generator?

You can't without consuming it. sum(1 for _ in gen) counts the items but uses the generator up. If you need the length and the values, use a list.

What to learn next

  1. Combine, slice and group iterators with the Python itertools module.
  2. Revise the protocol underneath in Python iterators and iterables.
  3. See lazy data loading at scale in the pandas DataFrame tutorial.