← Back to Computer Science Computer Science

Examples of Generators: 8 Python Snippets With Output

Which generator? This post covers Python generators, the yield kind. If you came for machines that turn motion into electricity (dynamos, alternators, turbines), the U.S. Energy Information Administration explains how they work.

A generator is a function that hands back values one at a time instead of building them all up front. It pauses at each yield, keeps its local variables, and picks up where it stopped when you ask for the next value.

That’s the whole idea. The eight examples below show it at work, in order of difficulty, with the output under every snippet. After them: a memory comparison with real numbers, and a list of cases where a generator is the wrong tool.

Table of Contents

What a generator does differently

Vibrant and engaging code displayed on a computer screen, showcasing programming concepts.

A normal function runs to the end, returns one value, and forgets everything. A generator function contains yield, so calling it returns a generator object without running any of the body. The body runs only when something asks for a value, through a for loop, next(), or a function like sum().

Generators have been in Python since version 2.2, introduced by PEP 255 in 2001. JavaScript has the same feature under the name function*, and the examples here translate almost line for line.

Two properties matter for everything that follows. Values are produced lazily, so nothing is computed until requested. And a generator is single-use: once it’s exhausted, it stays empty.

Example 1: A countdown with yield

The smallest useful generator.

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

for number in countdown(3): print(number) “`

Output:

3 2 1

Calling countdown(3) runs nothing. The loop calls next() behind the scenes, the function runs until it hits yield n, hands over the value, and freezes. When n reaches 0 the function ends, and Python raises StopIteration to tell the loop it’s finished. Call next() by hand on an exhausted generator and you’ll see that exception yourself.

Example 2: Fibonacci numbers

A classic because the state (the last two numbers) lives in plain local variables.

“`python def fibonacci(limit): a, b = 0, 1 while a < limit: yield a a, b = b, a + b

print(list(fibonacci(100))) “`

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

The version that returns a list needs a result = [] and an append() in every iteration. Here the function only says what the next value is. Drop the limit check and while True makes it endless, which is fine as long as the consumer decides when to stop.

Example 3: A generator expression

Same syntax as a list comprehension, with parentheses instead of square brackets.

python squares = (x * x for x in range(5)) print(next(squares)) print(next(squares)) print(sum(x * x for x in range(10)))

Output:

0 1 285

The first two lines pull values out one by one. The third feeds a generator expression straight into sum(), which needs no extra parentheses when it’s the only argument. No intermediate list exists at any point.

This is the quickest answer to “generator expression vs list comprehension”: use the comprehension when you need the list itself, and the generator expression when you’re going to loop over the result once.

Example 4: Reading a large file line by line

Say you have a multi-gigabyte telescope log and want only the warnings.

“`python def matching_lines(path, keyword): with open(path) as f: for line in f: if keyword in line: yield line.rstrip()

for line in matching_lines(“telescope.log”, “WARN”): print(line) “`

If the file contains a few warnings among millions of lines, the output looks like this:

2026-03-14 02:17:44 WARN dome shutter lag 2026-03-14 02:51:09 WARN guide star lost

Python reads the file lazily, one line at a time, and the generator passes along only the matches. Memory use stays flat whether the file is 5 MB or 50 GB. The with block closes the file when the generator finishes or is garbage-collected.

Example 5: An infinite ID generator

Generators can run forever because nothing forces them to finish.

“`python def id_generator(prefix=”SAMPLE”): n = 1 while True: yield f”{prefix}-{n:04d}” n += 1

ids = id_generator() print(next(ids)) print(next(ids)) print(next(ids)) “`

Output:

SAMPLE-0001 SAMPLE-0002 SAMPLE-0003

Each call to id_generator() creates an independent counter, so two lab benches can each have their own sequence. A global counter variable can’t do that without extra bookkeeping. To take a fixed number from an endless generator, use itertools.islice, covered in the itertools documentation.

Example 6: A pipeline of chained generators

Small generators that each do one job, connected end to end. This is where generators stop being a curiosity and start changing how you write code.

“`python def readings(): for c in [21.5, 22.0, -999, 23.1, 22.8, -999, 24.0]: yield c

def valid(stream): for t in stream: if t != -999: yield t

def to_kelvin(stream): for t in stream: yield round(t + 273.15, 2)

print(list(to_kelvin(valid(readings())))) “`

Output:

[294.65, 295.15, 296.25, 295.95, 297.15]

The value -999 is a common “sensor failed” marker in raw data. Each stage handles one reading at a time: a value flows from readings() through valid() and to_kelvin() before the next one is even requested. Nothing is stored between stages, so the same three functions work on seven readings or seven hundred million. Swap readings() for the file reader from Example 4 and the pipeline streams from disk.

Example 7: Two-way communication with send()

So far data only flowed out of the generator. send() lets you push values in. It was added in Python 2.5 by PEP 342.

“`python def running_average(): total = 0.0 count = 0 average = None while True: value = yield average total += value count += 1 average = total / count

avg = running_average() next(avg) print(avg.send(10)) print(avg.send(20)) print(avg.send(60)) “`

Output:

10.0 15.0 30.0

The next(avg) call is required. It runs the generator up to the first yield, so there’s a paused spot ready to receive a value. Skip it and Python raises a TypeError. After that, each send(x) becomes the result of the yield expression, the function updates its totals, and the new average comes back as the return value of send().

This is the mechanism early Python coroutines were built on, before async and await existed.

Example 8: Flattening nested lists with yield from

yield from hands control to another generator and passes its values straight through.

“`python def flatten(nested): for item in nested: if isinstance(item, list): yield from flatten(item) else: yield item

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

Output:

[1, 2, 3, 4, 5]

Without yield from, the recursive call would need its own inner for loop re-yielding every value. With it, the nesting depth doesn’t matter. The same pattern walks directory trees, XML elements, and taxonomies, which makes it handy for anything shaped like a tree.

Generator vs list: the memory numbers

Detailed view of a green electronic memory module against a white background, showcasing modern technology.

Here’s the same million squares built both ways, measured with sys.getsizeof:

“`python import sys

squares_list = [n * n for n in range(1_000_000)] squares_gen = (n * n for n in range(1_000_000))

print(sys.getsizeof(squares_list)) print(sys.getsizeof(squares_gen)) “`

On a typical 64-bit CPython build the first line prints about 8.4 million bytes. The second prints a few hundred bytes at most, and the exact figure shifts between Python versions. The generator’s size stays the same if you change the million to a billion.

Those 8.4 MB undersell the gap. getsizeof counts only the list’s own array of pointers, not the million integer objects it points to. Most of these squares need around 32 bytes each, so the real footprint of the list is on the order of 40 MB. To see the true peak for your own code, use the standard library’s tracemalloc module.

Speed is a different story. Producing a value through a generator costs slightly more than reading one from a list, so don’t expect generators to make a loop faster. The win is memory, plus the ability to start working on the first value before the last one exists.

When not to use a generator

Generators fit streams. They’re awkward almost everywhere else.

  • You need to loop more than once. A generator is spent after one pass:

python g = (x for x in range(3)) print(list(g)) print(list(g))

Output:

[0, 1, 2] []

The second pass silently returns nothing. That’s the most common generator bug, because no error is raised.

  • You need len(), indexing or slicing. g[2] and len(g) both raise TypeError. If you need random access, build a list.
  • The data is small. For a hundred items, a list is simpler and the memory saved is nothing.
  • You’re debugging. You can’t print a generator’s contents without consuming them. A list shows everything at once.
  • Several consumers share the stream. Two loops reading the same generator will split its values between them.

If a generator is the right shape but you need to reuse its output, wrap it in list() once and keep the result.

Which of these examples of generators to reuse first

Start with Example 4 and Example 6. Streaming a file through a chain of small generators is the case where beginners see the benefit most clearly, and it scales from a homework file to a production log without code changes. The rest are tools you’ll pick up as the need shows up: send() for stateful consumers, yield from for trees, and the infinite generator whenever you need an endless sequence that someone else will cut off.

The rule of thumb is short. If you’ll go through the data once, in order, and it might be large, write a generator. If you’ll touch it twice or need to jump around, use a list.

Avatar photo

Prof. Daniel Kowalski

Professor of Applied Mathematics with a joint appointment in Computer Science, currently on leave to focus on science communication. Published extensively on machine learning theory before discovering he enjoyed explaining algorithms to non-specialists more than optimizing them. Runs a popular video series on the mathematics hiding in everyday life. Believes that math anxiety is a bigger barrier to science literacy than any equation.

Post navigation