8-6. The yield Statement

The yield statement in Python is used within a function to create a generator. A generator is a special type of iterator that allows you to iterate through a sequence of values, producing them one at a time, only when requested. This is different from returning all values at once.

Basics of yield

When a function includes the yield statement, it becomes a generator function. Calling this function does not execute its code immediately. Instead, it returns a generator object. You can then use the next() function on this generator to get the next value produced by the generator.

 

Example 1: Fixed Result Generator

Here’s a simple generator function that yields the same string every time:

Output:

In this example, each call to next(myGenerator()) creates a new generator and yields "More research is needed…".

 

Example 2: Collection Generator

A more practical example of a generator function yields successive elements from a collection:

Output:

In this example:

  • The my_generator2 function takes a list (my_aliaslist) and yields each element one at a time.
  • yield from my_aliaslist is a shorthand for yielding each element in my_aliaslist.

Key Points of yield

  1. State Retention: Generators retain their state between calls. This means they remember where they left off in the iteration process.
  2. Lazy Evaluation: Generators produce items only when requested, which is useful for handling large datasets efficiently.
  3. Simplified Code: Using yield can make code more readable and maintainable compared to manually managing an iterator.