In Python, a generator is a special type of function that returns an iterator object. It is defined using the yield keyword instead of the return keyword, and allows you to generate a series of values on the fly, rather than computing and storing them all at once.
When a generator is called, it doesn't execute the entire function at once. Instead, it executes the code up until the first yield statement, and then pauses and returns the value. The next time the generator is called, it resumes execution where it left off, and continues until it reaches the next yield statement. This process continues until the end of the function is reached, or until the generator is explicitly stopped using the StopIteration exception.
Here's an example of a simple generator that yields the square of each number in a sequence:
def square_numbers(nums): for num in nums: yield num * num # Using the generator in a for loop my_nums = [1, 2, 3, 4, 5] for num in square_numbers(my_nums): print(num)
In this example, the square_numbers() function is a generator that takes a sequence of numbers and yields the square of each number. The for loop calls the generator function, and iterates over the values it generates.
Generators are useful for generating large sequences of data on the fly, without having to store them all in memory at once. They are also commonly used to generate data for streaming and other real-time applications.
0 Comments