matix.io

What does the yield keyword do in Python?

December 11, 2022

The yield keyword in Python is used to create generators. Generators are a type of iterable, like a list or a tuple. Unlike lists, however, generators do not store their elements in memory. Instead, they generate them on the fly, which makes them much more memory-efficient than lists.

The yield keyword is used to define a generator function. A generator function is similar to a regular function, but instead of returning a value, it yields one or more values. Here's an example of a simple generator function:

 


def my_generator():
    yield 1
    yield 2
    yield 3

 

This generator function yields the values 1, 2, and 3, one at a time. When the function is called, it doesn't return any value. Instead, it returns a generator object that can be used to iterate over the values that the generator function yields.

To iterate over the values yielded by a generator function, you can use a for loop:

 


for value in my_generator():
    print(value)

This for loop will print the values 1, 2, and 3, one at a time. As you can see, the yield keyword makes it easy to create and use generators in Python.

One advantage of using generators is that they are lazy. This means that the values are generated only when they are needed, which can save a lot of memory and processing time. This is especially useful when dealing with large datasets or complex calculations that would require a lot of memory if stored in a list.

Here's an example of a generator that calculates the Fibonacci sequence:


def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

 

This generator function uses the yield keyword to yield the next value in the Fibonacci sequence each time it is called. The while True loop ensures that the generator will continue to yield values indefinitely.

Another advantage of generators is that they can be composed. This means that you can use one generator as input to another generator, creating a pipeline of generators that can be used to perform complex operations on your data.

Here's an example of a generator that takes a generator as input and filters its values:


def even_numbers(numbers):
    for number in numbers:
        if number % 2 == 0:
            yield number

This generator function takes another generator as input and yields only the even numbers that are generated by the input generator. You can use this generator to filter any other generator that yields numbers.

In conclusion, the yield keyword in Python is used to create generators, which are a type of iterable that generates values on the fly instead of storing them in memory. Generators are lazy, which makes them memory-efficient, and they can be composed, which makes them powerful and flexible.