The yield keyword in Python is used in generator functions to create iterable generators. A generator is a type of iterator that allows you to iterate over a sequence of values one at a time, without having to store the entire sequence in memory at once.
When a generator function is called, it returns a generator object without actually running the function's code. The generator object can then be used to iterate over the sequence of values by calling its __next__() method (or using it in a for loop). Each time the __next__() method is called, the generator function's code is executed until it reaches a yield statement. The value of the expression following the yield keyword is returned as the next value in the sequence, and the state of the function is saved so that it can be resumed the next time __next__() is called.
Here's a simple example of a generator function that generates a sequence of even numbers:
def even_numbers(n): for i in range(n): if i % 2 == 0: yield i |
When this function is called with a value of n, it returns a generator object that can be used to iterate over the even numbers up to n. For example:
>>> for num in even_numbers(10):... print(num)02468 |
Each time the __next__() method is called on the generator object, the function's code runs until it reaches the yield statement, which returns the current even number in the sequence. The function's state is then saved so that it can be resumed the next time __next__() is called, and the iteration continues with the next even number in the sequence.
In summary, the yield keyword in Python is used to create iterable generators that allow you to iterate over a sequence of values one at a time, without having to store the entire sequence in memory at once.