How to Use Yield in Python

09/08/2021

Contents

In this article, you will learn how to use the yield statement in Python.

The yield statement

In Python, the yield statement is used to generate a sequence of values to be used in an iteration. Unlike a normal function which runs and returns a value, a generator function uses the yield statement to return a generator object that can be iterated over to generate a sequence of values.

Here’s a simple example:

def generator_example():
    yield 1
    yield 2
    yield 3

gen = generator_example()
for i in gen:
    print(i)

# Output:
# 1
# 2
# 3

In this example, the generator_example function is a generator function that uses the yield statement to generate values 1, 2, and 3. When you call this function, it returns a generator object, which you can iterate over using a for loop.

 

Here are a few more things you should know about using yield in Python:

Stateful Generation

When you use yield, the state of the function is saved and can be resumed later. This means that you can maintain the state of the function between function calls and generate values based on that state. This can be particularly useful when generating large sequences of values, as it allows you to generate them one at a time, rather than having to generate the entire sequence in memory at once.

Infinite Generators

With yield, you can also create infinite generators that generate values indefinitely.

For example:

def infinite_generator():
    i = 0
    while True:
        yield i
        i += 1

gen = infinite_generator()
for i in gen:
    print(i)

# Output:
# 0
# 1
# 2
# 3
# ...
Generator Expressions

In addition to generator functions, you can also use generator expressions, which are a compact way to create a generator by providing an expression that generates values.

Here’s an example:

gen = (x**2 for x in range(10))
for i in gen:
    print(i)

# Output:
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
# 64
# 81
Performance Benefits

By generating values one at a time, generators can be more efficient in terms of memory usage and processing time compared to other methods of generating sequences, such as lists. This is because generators only generate values as they are needed, rather than generating the entire sequence in memory at once.