0Pricing
Python Academy · Lesson

yield from and Delegation

Compose generators.

yield from and Delegation is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Problem yield from Solves

When one generator wants to yield every value from another iterable, you can write a manual loop. yield from does the same thing in one line.

def manual():
    for x in [1, 2, 3]:
        yield x

print(list(manual()))

Introducing yield from

yield from iterable delegates to that iterable, yielding each of its values in turn. It is shorter and clearer than a forwarding loop.

def delegate():
    yield from [1, 2, 3]

print(list(delegate()))

Combining Multiple Sources

You can chain several yield from statements to concatenate sequences lazily.

def chained():
    yield from 'ab'
    yield from [1, 2]
    yield from range(2)

print(list(chained()))

Delegating to Another Generator

The delegated iterable can itself be a generator, letting you compose generators into larger ones.

def evens(n):
    for i in range(n):
        if i % 2 == 0:
            yield i

def report(n):
    print('evens:')
    yield from evens(n)

print(list(report(6)))

Flattening Nested Lists

A classic use of yield from is recursive flattening: a generator that delegates to itself for sublists.

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])))

yield from vs a Loop

Both versions below produce the same output. yield from is preferred for readability and because it also forwards advanced features like sending values and return results.

def with_loop(src):
    for x in src:
        yield x

def with_yield_from(src):
    yield from src

print(list(with_loop(range(3))))
print(list(with_yield_from(range(3))))

Capturing a Subgenerator's Return

When a delegated generator returns a value, yield from evaluates to that value. This lets subgenerators report a result.

def counter(n):
    count = 0
    for i in range(n):
        yield i
        count += 1
    return count

def driver():
    total = yield from counter(3)
    print('subgen yielded', total, 'items')

list(driver())

Building a Pipeline

Delegation makes it easy to split a pipeline into named stages and compose them.

def source():
    yield from range(5)

def only_odd(src):
    for x in src:
        if x % 2 == 1:
            yield x

def pipeline():
    yield from only_odd(source())

print(list(pipeline()))

Delegating to Any Iterable

yield from works with any iterable, not just generators: lists, tuples, sets, strings, dict keys, and more.

def mixed():
    yield from {1, 2, 3}
    yield from ('a', 'b')

result = list(mixed())
print(sorted(str(x) for x in result))

Merging Generators in Order

You can build a generator that walks several sources sequentially, which is useful for joining streams.

def concat(*iterables):
    for it in iterables:
        yield from it

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

Readability Wins

For deeply nested or tree-like data, yield from keeps recursive generators short and intention-revealing.

def walk(tree):
    yield tree['name']
    for child in tree.get('children', []):
        yield from walk(child)

tree = {'name': 'root', 'children': [
    {'name': 'a'},
    {'name': 'b', 'children': [{'name': 'c'}]}
]}
print(list(walk(tree)))

Quick Check

Test your understanding of yield from.

Recap

You learned yield from and delegation:

  • It forwards every value from an inner iterable.
  • It composes generators and powers recursive flattening.
  • It captures the subgenerator's return value.
  • It is clearer than a manual forwarding loop.

Next course: concurrency with threading and multiprocessing.

Frequently asked questions

Is the “yield from and Delegation” lesson free?

Yes — the full text of “yield from and Delegation” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “yield from and Delegation”?

Compose generators. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “yield from and Delegation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Iterator Protocol
  2. Generator Functions
  3. Generator Expressions
  4. yield from and Delegation
← Back to Python Academy