Skip to content
Home / Fundamentals

What does yield do in Python

In Python, the yield keyword is used in the body of a function like a return statement, but instead of returning a value and exiting the function, yield generates a value and suspends the function's execution, allowing the function to be resumed later on. This is useful for creating iterators, which are objects that allow you to iterate over a sequence of values, such as a list or a range.

Here's an example of a simple function that uses yield to generate a sequence of numbers:

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)

This code defines a function count_up_to that takes a maximum value as an argument and generates a sequence of numbers from 1 to that value. The yield statement is used to generate each number in the sequence, and the function is suspended after each yield until it is resumed.

When the function is called in the for loop, it starts executing at the beginning and runs until it encounters the first yield statement. At this point, the function generates the value 1 and suspends its execution. The for loop then prints the value and the function is resumed from the point where it was suspended. This process is repeated until the function has reached the end of its execution and all the values have been generated and printed.

Here's the output of the above code:

1
2
3
4
5

You can also use the yield keyword in combination with a for loop to generate a sequence of values from a list or any other iterable object:

def generate_values(values):
    for value in values:
        yield value

for value in generate_values([1, 2, 3, 4, 5]):
    print(value)

This code defines a function generate_values that takes a list of values as an argument and generates those values one by one using a for loop and the yield keyword. When the function is called in the for loop, it starts executing at the beginning and runs until it reaches the end of the for loop. At each iteration, the function generates the current value and suspends its execution until it is resumed.

Here's the output of the above code:

1
2
3
4
5