1. Home
  2. Blog
  3. Software Development

Software Development

Python Generators and Yield Explained: Save Memory With Real Examples

Generators produce values one at a time instead of building a whole list in memory. Watch exactly how yield pauses a function, see the memory difference we measured, and build a small data pipeline.

9 min read
Python generators and yield explained: save memory with real examples

Key takeaways

  • A function containing yield returns a generator, and its body does not run until you ask for a value.
  • yield pauses the function and keeps its local state until the next request.
  • Generators use a small, fixed amount of memory however many values they produce.
  • A generator can be consumed only once, which is the most common trap.

Imagine loading a 10 GB log file into a list just to find the errors. Your program may run out of memory before it finds one. Python generators solve that by producing values on demand, one at a time, so you can work through huge or even endless data with almost no memory.

This guide shows what really happens when a generator runs, step by step. We ran each example on Python 3.13, and the output comes from that run. It helps to already be comfortable with functions and loops, which our Python tutorial for beginners covers.

What is a generator?

A generator is a special kind of iterator that you create by writing a function using yield. Any function with yield in it automatically becomes a generator function, and calling it gives you a generator object rather than running the code.

def count_up(limit):
    print("starting")
    n = 1
    while n <= limit:
        yield n
        n += 1
    print("finished")

gen = count_up(2)
print(gen)

# <generator object count_up at 0x...>

Notice that “starting” did not print. Calling the function only created the generator. Nothing inside has run yet.

How yield works, step by step

Each call to next() runs the function until it reaches a yield, hands back that value, and freezes in place. The next call resumes right after that line, with every local variable intact.

print(next(gen))
# starting
# 1

print(next(gen))
# 2

next(gen)
# finished
# StopIteration

Follow the output carefully. “starting” appears only on the first next(). On the second, execution continues from where it stopped, so n is still available and becomes 2. On the third, the loop ends, “finished” prints, the function falls off the end, and Python raises StopIteration to signal that there is nothing left.

You rarely call next() yourself. A for loop does it for you and handles StopIteration quietly, and so do list(), sum() and similar functions:

print(list(count_up(3)))

# starting
# finished
# [1, 2, 3]

yield vs return

Aspect return yield
What it does Ends the function Pauses the function
Values produced One result A series, one at a time
Local state Discarded Preserved between values
When the code runs Immediately when called Only when a value is requested
Memory for many values Must hold them all Holds one at a time

This delay is known as lazy evaluation: values are worked out only when needed. A plain return inside a generator simply ends it, which triggers StopIteration.

The memory difference, measured

We compared a list of one million squares with an equivalent generator, using sys.getsizeof:

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), sys.getsizeof(squares_gen))

# 8448728 200

The list’s own structure took about 8.4 MB, while the generator took just 200 bytes on our system. The real gap is even bigger, as getsizeof does not count the integer objects inside the list. The generator’s size also stays the same for a billion items, since it stores only its current state and not its results.

There is a trade-off, though. A list can be reused, indexed and measured with len(). A generator offers none of these. If you need random access, or you will loop several times over a small amount of data, a list is simpler. See our guide to Python list vs tuple vs set for more on those types.

Generator expressions

For simple cases, you do not need a function. A generator expression looks like a list comprehension with round brackets in place of square ones:

squares = [n * n for n in range(5)]   # builds a list now
squares = (n * n for n in range(5))   # produces values on demand

print(sum(n * n for n in range(5)))

# 30

When a generator expression is the only argument to a function, as in sum(), you can leave out the extra brackets. This is a tidy habit for totals over large data, because no temporary list is created.

Build a data pipeline

This is where generators really shine. Small generators can be chained so that each item flows through every step, one at a time:

def read_lines(lines):
    for line in lines:
        yield line.strip()

def only_errors(lines):
    for line in lines:
        if line.startswith("ERROR"):
            yield line

def messages(lines):
    for line in lines:
        yield line.split(" ", 1)[1]

log = ["INFO started\n", "ERROR db down\n",
       "ERROR disk full\n", "INFO stopped\n"]

print(list(messages(only_errors(read_lines(log)))))

# ['db down', 'disk full']

Each step does one small job and can be tested on its own. In real use, swap the sample list for an open file, because file objects can be read line by line, as our guide to Python file handling shows. Even a multi-gigabyte log would then pass through with very little memory.

Tip: A pipeline does no work until something consumes it. Building the chain is instant. The processing happens only when you loop over the final generator or wrap it in a call like list().

Infinite sequences

A list cannot be infinite, but a generator can, because it only ever computes the next value. Use itertools.islice to take as many as you need:

import itertools

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

print(list(itertools.islice(fibonacci(), 8)))

# [0, 1, 1, 2, 3, 5, 8, 13]

Be careful, though: calling list(fibonacci()) without a limit would run until your memory is gone. The same pattern suits ID generators, polling loops and paginated API results, where you fetch the next page only when the current one runs out.

yield from and batches

yield from hands off to another iterable, saving you a nested loop:

def chain_all(*groups):
    for group in groups:
        yield from group

print(list(chain_all([1, 2], (3, 4))))

# [1, 2, 3, 4]

A very practical pattern is splitting data into fixed-size batches, for example to insert rows into a database a thousand at a time:

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(7), 3)))

# [[0, 1, 2], [3, 4, 5], [6]]

The final if batch makes sure that a smaller leftover group is not lost. Python 3.12 and later also include itertools.batched, which does a similar job.

send, close and cleanup

Generators can also receive values. send() resumes the generator, and the value becomes the result of the yield expression. You must call next() once first to reach the first yield:

def running_total():
    total = 0
    while True:
        value = yield total
        total += value

t = running_total()
next(t)
print(t.send(10), t.send(5))

# 10 15

Most people seldom need this. A more common concern is cleanup. If you stop early, a finally block still runs when the generator is closed:

def tracked():
    try:
        yield 1
        yield 2
    finally:
        print("cleanup ran")

tr = tracked()
next(tr)
tr.close()

# cleanup ran

Pytest uses this very idea: a fixture with yield runs its cleanup afterwards, as our pytest tutorial demonstrates. Likewise, the standard library’s contextmanager decorator turns a generator into a with block.

Generators in classes

Writing an __iter__ method as a generator is the easiest way to make your own class iterable. A bonus is that each loop gets a fresh generator, so the object can be looped over again and again:

class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

c = Countdown(3)
print(list(c), list(c))

# [3, 2, 1] [3, 2, 1]

When to use a generator

Use a generator when Use a list when
Data is large or its size is unknown Data is small and fits in memory
You process items once, in order You loop several times
You may stop early You need len(), indexing or slicing
You are reading a stream or files You need to sort or reverse the data
You are building a pipeline Simplicity matters more than memory

A generator is not always faster overall. If you end up using every value, the total work is similar, and a list comprehension can even be quicker for small data because it has less per-item overhead. The main benefits are memory use, and getting the first results sooner.

Common mistakes

Reusing an exhausted generator

This catches nearly everyone at some point. A generator remembers that it is finished:

g = count_up(2)
print(list(g), list(g))

# [1, 2] []

The second call gets an empty list with no error at all. Call the function again to get a new generator, or use the class approach shown above.

Expecting code to run immediately

def noisy():
    print("body runs")
    yield 1

n = noisy()        # nothing is printed
print(next(n))     # body runs, then 1

Argument checks at the top of a generator do not run until the first next(), so errors can appear far from the call that caused them.

Other traps

  • Calling len() or indexing. Generators support neither, and raise a TypeError.
  • Closing a file too soon. Returning a generator from inside a with block can mean the file closes before any line is read. Put the yield inside the with block.
  • Wrapping everything in list(). That throws away the memory benefit.
  • Using one for tiny data. A plain list is often clearer.

Final thoughts

A generator is a function that can pause. That one idea gives you low memory use, endless sequences and clean pipelines. To put it into practice, find a place in your code that builds a large list only to loop over it once, and turn that into a generator. Then try chaining two small generators together on a real log file.

Frequently asked questions

What does yield do in Python?

yield produces a value and pauses the function, keeping its local variables. The function resumes from the same point when the next value is requested.

What is the difference between a generator and a list?

A list stores all its values in memory at once. A generator computes each value on demand, uses little memory and can usually be consumed only once.

What is the difference between an iterator and a generator?

Every generator is an iterator. A generator is simply the easiest way to write one, as Python creates the __iter__ and __next__ methods for you.

Can you loop over a generator twice?

No. Once exhausted, it yields nothing more, without raising an error. Create a new generator by calling the function again, or store the results in a list.

Are generators faster than lists?

Not always. They use far less memory and deliver the first result sooner, but a list comprehension can be slightly quicker when you consume small amounts of data entirely.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →