Skip to content

Python yield statement | Example code

  • by

The python yield statement is used in a function to return the generator object. Using yield instead of returning 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

In 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=" ")

Output:

Python yield statement

Difference between yield and return

ReturnYield
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 or suggestions on this Python yield tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *