CodeBlanks Logo Icon CodeBlanks

yield from

Learn delegation with yield from.

yield from

yield from publishes another generator or iterable as if it were part of the current generator. It is used to flatten nested generators.

Example: def outer():\n yield 0\n yield from inner()\n yield 3. Here all values from inner() are published through outer() in order. It gives the same result as for v in inner(): yield v but is shorter and more efficient.

Efficiency advantage

yield from is not only a shortcut but also an efficient construct. Python wires the inner generator directly to the caller; no intermediate frame is created for each value.

This makes a real difference in recursive generators. Example: a generator that visits all leaves of a tree lazily walks subtrees with yield from. The memory and speed advantage is large; it shows on deep data.

Practice Flatten with yield from

Define the function def inner():; in the body write yield 1 and yield 2. Define the function def outer():; in the body write yield 0, yield from inner() and yield 3. Then print all values with print(list(outer())).

Starter code

main.py
# Publish an inner generator with yield from

Sample solution

main.py
# Publish an inner generator with yield from
def inner():
    yield 1
    yield 2

def outer():
    yield 0
    yield from inner()
    yield 3

print(list(outer()))

Expected output

[0, 1, 2, 3]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does yield from do?

  • Produces only a single value
  • Stops the generator
  • Publishes all values from an inner generator Correct answer
  • Creates a new generator

Explanation: yield from publishes all values from an inner generator in order.

2 yield from line

Question
def outer():
    yield 0
    ____ inner()
    yield 3
Answer
def outer():
    yield 0
    yield from inner()
    yield 3

Explanation: yield from publishes the inner generator.

3 Match the yield from parts

Term Meaning
yield from Inner publishing
inner() Inner generator
outer() Outer generator
list(outer()) Result list

All lessons in Intermediate