0Pricing
Python Academy · Lesson

yield from and Delegation

Compose generators.

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

All lessons in this course

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