Python Generator
In Python, a generator is a function that produces a sequence of values using the yield
keyword instead of return
. It can be used to generate a large amount of data on-the-fly, without storing it in memory.
A generator function is defined like a normal function, but instead of returning a value, it yields a value. When a generator function is called, it returns a generator object that can be iterated over using a for
loop or the next()
function.
Here's an example of creating a generator that generates the squares of a list of numbers:
def square_numbers(nums): for num in nums: yield num ** 2 my_nums = [1, 2, 3, 4, 5] # create a generator object my_generator = square_numbers(my_nums) # iterate over the generator using a for loop for num in my_generator: print(num)Sourc.www:etheitroad.com
Output:
1 4 9 16 25
In the above example, we defined a generator function square_numbers
that takes a list of numbers as input and yields the squares of those numbers one at a time using the yield
keyword.
We then created a generator object my_generator
by calling the square_numbers
function with a list of numbers [1, 2, 3, 4, 5]
. We iterated over the generator object using a for
loop, which calls the generator function to yield the next value in the sequence.
Note that generators are lazy evaluated, which means that they only generate the next value when it is requested. This makes them memory efficient, as they do not generate the entire sequence at once.