In Python, the yield keyword is used in a function to turn it into a generator. When a generator function is called, it returns a generator object that can be used to iterate over a sequence of values.
When the yield keyword is encountered in a function, the current value is returned to the caller, but the function's state is saved. This allows the function to be resumed later from where it left off, rather than starting over from the beginning.
Here's an example of a generator function that uses the yield keyword to generate a sequence of numbers:
def my_generator():
for i in range(5):
yield i
gen = my_generator()
for num in gen:
print(num)
In this example, my_generator is defined with a loop that yields each value of i in turn. When my_generator is called, it returns a generator object that can be used to iterate over the sequence of numbers. The for loop then iterates over the generator object and prints each number in turn.
The use of generators can be more memory-efficient than returning a list of all the values at once, particularly when dealing with large or infinite sequences of values.
Comments (0)