Python yield statement | Example code

The python yield statement is used in a function to return the generator object. Using yield instead of return the function instead of returning the output, it returns a generator that can be iterated upon.

You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.

Example yield statement in Python

Simple example code the yield enables the function to remember its ‘state’, this function can be used to generate values in a logic defined by you. So, its function becomes a ‘generator’.

Generator to print even numbers.

def print_even(lst):
    for i in lst:
        if i % 2 == 0:
            yield i

lst = [1, 4, 5, 6, 8]

for j in print_even(lst):
    print(j, end=" ")


Python yield statement

Difference between yield and return

Returns the result to the callerUsed to convert a function to a generator. Suspends the function preserving its state
Destroys the variables once execution is completeYield does not destroy the function’s local variables. Preserves the state.
There is usually one return statement per functionThere can be one or more yield statements, which is quite common.
If you execute a function again it starts from the beginningThe execution begins from where it was previously paused

Do comment if you have any doubts and suggestions on this Python yield tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.