What does the 'yield' keyword do?

In Python, the yield keyword is used in a function to create a generator, a special type of iterable that generates values lazily. When a function contains the yield keyword, it becomes a generator function, and calling it doesn't execute the function immediately. Instead, it returns a generator object that can be iterated over using a loop or other iteration mechanisms.

Python yield keyword

The primary benefit of using yield is that it allows you to generate values on-the-fly, saving memory and improving performance for large datasets.

def generate_numbers(n): for i in range(n): yield i # Using the generator function numbers_generator = generate_numbers(5) for num in numbers_generator: print(num)

In the above example, the generate_numbers function is a generator function that yields numbers from 0 to n-1. When you call generate_numbers(5), it doesn't execute the loop immediately. Instead, it returns a generator object, which you can then iterate over in a loop. The loop pulls values from the generator one at a time as needed, without generating all the values at once.


The use of yield is particularly beneficial when dealing with large datasets or situations where generating all the values at once is memory-intensive. It allows you to create memory-efficient code by producing values on-the-fly, as opposed to creating a list of all values in memory.