Full Byte Developer.

Python yield and iterators

A yield function returns a generator that pauses and resumes; it streams values instead of building a full list.

Published here , updated · 5 sources

Generators are functions that return an iterator streaming values instead of one finished result [1]. Any function that uses yield is compiled as a generator function that pauses and then resumes later on each next call [1]. Related next: python async def is lazy.

Quick start (under a minute)

Paste this into a REPL or file:

python
def three():
    yield 1
    yield 2
    yield 3

for x in three():
    print(x)

You should see 1, 2, and 3 on separate lines. The function paused after each yield and resumed when the for loop asked for the next item [1].

Run the HOWTO counter on this host

The functional HOWTO starts with a tiny counting generator [1]:

python
def range_count(n):
    i = 0
    while i < n:
        yield i
        i += 1

g = range_count(3)
print("generator", g)
print(next(g), next(g), next(g))
try:
    next(g)
except StopIteration:
    print("StopIteration")

Observed on this draft host (Python 3.12.3, 2026-12-03):

text
generator <generator object range_count at 0x7f20a7f007c0>
0 1 2
StopIteration

Calling range_count(3) did not run the whole loop. It returned a generator object [1]. Each next ran until the next yield, then suspended with locals (i) preserved [1] [2]. The fourth next raised StopIteration, which a for loop catches quietly [1].

PEP 255 introduced this suspend and resume model for iterators that are cheap to write [3]. Generator expressions (x * x for x in data) compile to the same machinery in a single expression [1].

Picture pause and resume (not a second stack)

State lives on the generator object. That is why generators suit pipelines: you do not need a full list in memory between stages [1].

Treat yield as pause, not finish

ConstructWhat happens [1] [2]
yield valueProduce value, suspend, keep state
return value inside generatorEnds iteration (value goes to StopIteration in 3.3+)
Fall off endStream ends with StopIteration

yield from delegates to another iterable or generator, flattening nested iteration without copying everything into a list [1]. Use it when a wrapper generator mostly forwards another source.

Prefer for-loops over manual next

Consume generators with for value in g: so Python drives __next__ and handles StopIteration [1]. Use manual next when teaching or when you need one peek.

Exhausted generators do not restart. Call range_count(3) again for a fresh object [1]. Lists restart because you can iterate them multiple times; generators are single-pass unless you tee or rebuild.

Keep generators separate from async and parallelism

Generators are synchronous iterators. async def builds coroutines for the event loop (python-async-def-is-lazy). async for awaits async iterators; do not sprinkle yield and expect concurrency.

Generators do not bypass the GIL for CPU-bound Python loops. For parallel compute, use processes or native extensions (python-multiprocessing-vs-threading).

Stream a large file without a list

The HOWTO motivation is memory [1]. Compare building a list of lines versus yielding them:

python
def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n")

A consumer that stops early never reads the rest of the disk file through your generator. A readlines() call allocates for the whole file up front. On this draft host, the pattern is standard library only (no extra install).

The iterator protocol also powers map, file objects, and range in Python 3. Generators are one way to implement __iter__ without a class [1] [2].

send() and two-way generators (one paragraph)

Advanced generators can receive values with generator.send(value) after the first next [2]. That enables coroutine-like protocols before async def existed. Modern asyncio code should use async def for I/O-bound work instead of hand-rolled generator coroutines, but reading older libraries may still show yield used as a suspend point for sent values.

Generator expressions in pipelines

Chain lazy stages without nesting lists [1]:

python
nums = range(1_000_000)
squares = (n * n for n in nums)
evens = (n for n in squares if n % 2 == 0)
first = next(evens, None)

Nothing materializes a million-square list. Each stage pulls on demand. Profiling a data job often shows generators winning when the consumer stops early (first match, take N, break on error).

Close and cleanup

Generators support close() to inject GeneratorExit at the suspended yield [2]. Files opened inside a generator should use try/finally or context managers so close() paths still release descriptors. That matters when you wrap network iterators that outlive one request.

itertools without reinventing wheels

The standard itertools module builds on the iterator protocol: islice, chain, groupby [1]. Reach for those before writing custom generator classes. They behave as single-pass iterators unless documented otherwise.

Measure memory shape on this host (teaching only)

python
import sys
N = 500_000
big_list = list(range(N))
gen = (x for x in range(N))
print("list bytes", sys.getsizeof(big_list))
print("gen bytes", sys.getsizeof(gen))

Observed on this draft host (Python 3.12.3, 2026-12-03):

text
list bytes 4000056
gen bytes 192

getsizeof counts container overhead, not every referenced integer object for the list [1]. The generator stays tiny because values are produced lazily. Use this demo to justify generators in reviews, not as a universal benchmark.

When a list is still the right tool

Random access, sorting, binary search, and len() without consuming the sequence favor lists or arrays [1]. ETL jobs that must rerun from checkpoint often snapshot to disk instead of holding either structure in RAM. Generators fit streaming transforms; lists fit finished collections you revisit.

yield from and delegating iteration

When a wrapper generator mostly forwards another iterable, yield from inner avoids manual for loops and propagates send/throw correctly [2]. That matters in protocol stacks where one layer wraps another without copying items into an intermediate list.

Typing note: return type hints often use Iterator[int] or Generator[int, None, None] in modern codebases so callers know a function streams rather than returns a finished list. Static checkers treat that distinction as part of the public API, not commentary.

PEP 255's historical motivation was pushing iterator logic into readable functions without building iterator classes for every ad hoc sequence [3]. That design goal still matches log tailers, paginated API readers, and chunked uploads.

Where people go wrong

Building a list "for clarity" when you only iterate once. list(gen()) defeats streaming and spikes memory on large inputs.

Reusing an exhausted generator. Symptoms look like "sometimes it prints nothing." Create a new generator or materialize once intentionally.

Confusing generator functions with generator expressions. def f(): yield x returns a fresh generator per call. (x for x in data) is already an object; there is no function to call again.

Expecting return inside a generator to return to the caller like normal functions. In modern Python, return finishes the iterator; older tutorials may still say "return is illegal" which is outdated for 3.3+ [2].

Using generators where async I/O fits. Waiting on sockets belongs in coroutines and await, not blocking yield loops.

Rewrite one list comprehension as a generator and compare peak RSS on a large range. Time list(range(N)) versus a generator expression once so the memory demo in this page lands in a code review. Lazy I/O belongs on the event loop in python async def is lazy; CPU-bound Python still needs python multiprocessing vs threading when a generator loop cannot escape the GIL. For the JavaScript async/await cousin of cooperative pause points, see JavaScript async/await under the hood.

Send this to the friend who materializes a million-row list when a generator would stream.

Metallic dual row frame with glowing teal and amber slots, teal arrow and sphere entering left, outlined arrow and amber sphere leaving right, no people.
yield pauses the frame; the consumer drives resume with next or for.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

What makes a function a generator?

Python's functional HOWTO: any function containing yield is a generator function. Calling it returns a generator iterator object immediately; the function body has not finished yet. Iteration drives the body forward.

How is yield different from return?

yield produces a value and suspends, keeping local variables for the next step. return (or falling off the end) ends the generator and raises StopIteration to the consumer. You can yield many times; return exits once.

When should I use a generator?

When you need a lazy stream: large files, infinite sequences, pipeline stages, or values you might not consume fully. Use a list when you need random access, length, or multiple passes without recomputing.

Is this the same as async def?

No. Generators pair with yield and synchronous iteration. Coroutine functions use async def and await on an event loop. See python async def is lazy. Parallel CPU work still needs processes or native code that releases the GIL.

Sources

Next in this stack