# Python yield and iterators

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

Source: https://fullbytedeveloper.com/blog/python-yield-iterators
Published here: 2026-12-03, updated 2026-12-03

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](/blog/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)

<figure aria-label="Generator pause and resume on each next call">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 240" role="img" aria-hidden="true">
  <defs>
    <marker id="pythonyielditerators-gen-arr" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
      <path d="M0,0 L8,4 L0,8 Z" fill="#14b8a6"/>
    </marker>
  </defs>
  <rect x="0" y="0" width="360" height="240" rx="12" fill="#0b1f3a"/>
  <rect x="115.714" y="7.5" width="128.571" height="45" rx="4" fill="#123052" stroke="#14b8a6" stroke-width="0.964286"/>
  <text x="180" y="34" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">call range_count(3) [1]</text>
  <line x1="180" y1="48" x2="180" y2="64" stroke="#14b8a6" stroke-width="0.964286" marker-end="url(#pythonyielditerators-gen-arr)"/>
  <rect x="102.857" y="59.5" width="154.286" height="45" rx="4" fill="#123052" stroke="#14b8a6" stroke-width="1.28571"/>
  <text x="180" y="86" text-anchor="middle" font-size="12" font-weight="600" fill="#e6edf7" font-family="system-ui,sans-serif">generator object G</text>
  <text x="180" y="100" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">body not finished [1]</text>
  <line x1="180" y1="100" x2="77.1429" y2="128" stroke="#14b8a6" stroke-width="0.964286" marker-end="url(#pythonyielditerators-gen-arr)"/>
  <line x1="180" y1="100" x2="180" y2="128" stroke="#14b8a6" stroke-width="0.964286" marker-end="url(#pythonyielditerators-gen-arr)"/>
  <line x1="180" y1="100" x2="282.857" y2="128" stroke="#14b8a6" stroke-width="0.964286" marker-end="url(#pythonyielditerators-gen-arr)"/>
  <rect x="30.8571" y="119" width="92.5714" height="90" rx="4" fill="#123052" stroke="#14b8a6" stroke-width="0.964286"/>
  <text x="77.1429" y="152" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">next(G)</text>
  <text x="77.1429" y="168" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">run to yield</text>
  <text x="77.1429" y="184" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">suspend locals [1]</text>
  <rect x="133.714" y="119" width="92.5714" height="90" rx="4" fill="#123052" stroke="#14b8a6" stroke-width="0.964286"/>
  <text x="180" y="152" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">next(G)</text>
  <text x="180" y="168" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">resume frame</text>
  <text x="180" y="184" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">yield next value</text>
  <rect x="236.571" y="119" width="92.5714" height="90" rx="4" fill="#123052" stroke="#14b8a6" stroke-width="0.964286"/>
  <text x="282.857" y="152" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">exhausted</text>
  <text x="282.857" y="168" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">StopIteration</text>
  <text x="282.857" y="184" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">for-loop ends [1]</text>
  <text x="180" y="228" text-anchor="middle" font-size="12" fill="#e6edf7" font-family="system-ui,sans-serif">not the same as async def; see lazy coroutines separately</text>
</svg>
</figure>

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

| Construct | What happens [1] [2] |
|---|---|
| `yield value` | Produce `value`, suspend, keep state |
| `return value` inside generator | Ends iteration (value goes to StopIteration in 3.3+) |
| Fall off end | Stream 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](/blog/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](/blog/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](/blog/python-async-def-is-lazy); CPU-bound Python still needs [python multiprocessing vs threading](/blog/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](/blog/javascript-async-await-under-the-hood).

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

Image: 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.
https://fullbytedeveloper.com/media/python-yield-iterators/python-yield-iterators-venice.webp
yield pauses the frame; the consumer drives resume with next or for.

## Sources

1. [Python HOWTO: Functional Programming - Generators, accessed 2026-12-03](https://docs.python.org/3/howto/functional.html#generators)
2. [Python docs: yield expression, accessed 2026-12-03](https://docs.python.org/3/reference/expressions.html#yield-expressions)
3. [PEP 255: Simple Generators, accessed 2026-12-03](https://peps.python.org/pep-0255/)
4. [Full Byte Developer: Python async def is lazy](https://fullbytedeveloper.com/blog/python-async-def-is-lazy)
5. [Full Byte Developer: Python multiprocessing vs threading](https://fullbytedeveloper.com/blog/python-multiprocessing-vs-threading)
