Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 12 of 13

yield

The yield statement in detail: yielding values from loops, multiple yields, yield from for delegation, generator return values, and the difference between yield and return.

Beginner 10 min read·Lesson 156 of 306 in Python Programming

Learning objectives

  • Use yield inside loops and conditions
  • Delegate to sub-generators with yield from
  • Contrast yield with return

Definition

yield is a keyword used inside a function to produce a value to the caller and suspend the function's execution, which resumes after the yield on the next request. yield from iterable yields every value of another iterable.

Introduction

return hands back one value and ends the function. yield hands back a value and pauses, ready to continue. A generator can yield as many times as it likes.

Why it matters

yield from makes it easy to compose generators and to walk recursive structures such as folder trees or nested lists lazily.

Detailed explanation

A generator can contain several yield statements; they produce values in the order they are reached.

yield inside a loop produces one value per iteration — the most common pattern.

yield from iterable is shorthand for: for item in iterable: yield item. It's ideal for delegating to another generator, including the same function recursively.

return inside a generator ends it (raising StopIteration). A return value becomes the value of a yield from expression in the caller, which is rarely needed in everyday code.

Because the function's state is kept between yields, generators naturally express processes with steps, such as tokenisers or state machines.

Syntax

Python
def numbers():
yield 1
yield 2
yield from [3, 4]
def walk(tree):
for node in tree:
if isinstance(node, list):
yield from walk(node) # recursive delegation
else:
yield node
  • Each yield produces one value.
  • yield from produces all values of an iterable.
  • return ends the generator.

Code examples

Several yields and yield from

Python
def numbers():
yield 1
yield 2
yield from [3, 4]
yield from range(5, 7)
print(list(numbers()))
Output
[1, 2, 3, 4, 5, 6]

yield versus return

Python
def first_with_return(items):
for x in items:
return x
def all_with_yield(items):
for x in items:
yield x
print(first_with_return("abc"))
print(list(all_with_yield("abc")))
Output
a
['a', 'b', 'c']

More examples

Recursive generators

Python
def flatten(items):
for item in items:
if isinstance(item, (list, tuple)):
yield from flatten(item)
else:
yield item
nested = [1, [2, [3, 4], 5], (6, [7]), 8]
print(list(flatten(nested)))
tree = {"src": {"main.py": 120, "utils": {"io.py": 40, "math.py": 75}}, "README.md": 12}
def files(node, path=""):
for name, child in node.items():
if isinstance(child, dict):
yield from files(child, path + name + "/")
else:
yield path + name, child
for p, size in files(tree):
print(f"{p:<18}{size:>4}")
print("total", sum(size for _, size in files(tree)))
Output
[1, 2, 3, 4, 5, 6, 7, 8]
src/main.py        120
src/utils/io.py     40
src/utils/math.py   75
README.md           12
total 247

Step-by-step explanation

  • flatten yields plain items and delegates nested lists or tuples to a recursive call with yield from.
  • files walks a dictionary that models a folder tree, building each file's path as it goes.
  • Because files is a generator, sum can total the sizes without building a list.
  • Calling files(tree) again starts a fresh walk.

Expected output

Running “Recursive generators” prints exactly:

TextOutput
[1, 2, 3, 4, 5, 6, 7, 8]
src/main.py 120
src/utils/io.py 40
src/utils/math.py 75
README.md 12
total 247

Practical applications

  • Walking directory trees (os.walk is itself a generator).
  • Flattening nested JSON for export to CSV.

Best practices

  • Use yield from to delegate instead of an explicit inner loop.
  • Write recursive generators for tree-shaped data.
  • Keep generator functions focused on producing values.

Common mistakes

Forgetting yield from in recursion

Avoid

if isinstance(item, list):
flatten(item) # creates a generator and discards it

Prefer

if isinstance(item, list):
yield from flatten(item)

Calling a generator function returns a generator; you must yield its values.

Yielding a list instead of its items

Avoid

yield sub_items

Prefer

yield from sub_items

yield produces the whole list as one value; yield from produces each element.

Important notes

  • Generators also support send() and close(), used for coroutines; modern async code uses async/await instead.

Key takeaways

  • yield produces a value and pauses; return ends the generator.
  • A generator can yield many times.
  • yield from delegates to another iterable or generator.

Try it yourself

  1. 1
    Write a generator that yields every key path in a nested dictionary, like 'a.b.c'.
  2. 2
    Write chain(*iterables) using yield from.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic