liveBook · Manning

Yield

As explained in Python Workout: 50 ten-minute exercises

yield is a Python statement that produces a value from a generator function while suspending its execution until the next value is requested.

When a function must produce values one at a time instead of building a complete list, yield turns it into a generator function. Calling it returns a generator object; iteration runs until yield produces a value, then suspends execution until the next value is requested. section 10.0

A generator using yield behaves as follows:

  • Calling the function creates a generator object without immediately executing its body. section 10.0
  • Each next request resumes execution at the suspended point and continues through the next yield. section 10.0
  • Reaching the end of the generator ends iteration automatically with StopIteration; return exits the generator instead of producing another value. section 10.15
  • Local variables retain their values between yields, allowing a generator to remember progress across iterations. section 10.17

A three-value generator

def foo(): yield 1 yield 2 yield 3 g = foo() for value in g: print(value) The loop prints 1, 2, and 3. Each iteration advances g to the next yield, while the function keeps its position between iterations. section 10.0

Streaming filtered input

A generator can read a file one line at a time, yield only lines containing a desired string, and pause immediately after each matching line. This avoids collecting all matching lines before the caller can use them. section 10.12

Keeping state between results

A timing generator can calculate the elapsed time since its previous iteration, set last_time before yielding (delta, item), and reuse that retained value on the next request. section 10.17

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains suspension, resumption, automatic termination, and retained locals, while contrasting generators with explicit iterator classes.
Examples
Demonstrates numbered values, filtered file lines, retained timing state, and chaining multiple iterables.
What it assumes
Introduces the distinction between iterable and iterator objects alongside for loops, next, __iter__, and __next__.
What you can do after
Builds generators that stream values, preserve state, filter input, and combine iterables without implementing iterator methods manually.
How it connects
Connects yield with generators, iterators, next, StopIteration, return, iterable objects, and the iterator protocol.

Also explained in

Compare how 10 books explain yield →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.