What does the "yield" keyword do in Python?

Better Stack Team
Updated on January 13, 2023

To better understand what yield does, you need first to understand what generator and iterable are.

What is iterable

When you use a list or list-like structure, you can read the values from the list one by one. This is called iteration.

list_of_numbers = [1,10,100,1000]

# iterating over the list
for i in list_of_numbers:

This is why in many languages, the iterating variable is usually named i, but it can be named however you like. In short, basically, anything that can be used in for _ in _ is iterable.

What is generator

Generators are special kinds of iterables. They don’t store the values in memory, but rather generate the value on the fly. This means you can only iterate over them once.

generator = (x + 1 for x in range(4))

for i in generator:

What is yield

Finally the yield keyword. yield is used like return but instead of returning a single value it returns a generator. This is very useful when your function will return a huge set of values that you don’t want to store in memory.

def create_generator(n):
    for i in range(n):
        yield n + 1

generator = create_generator(4)

for i in generator:

In the example above, when calling the function create_generator, the function doesn’t return, instead, it creates a generator object.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →