Curriculum
Generator functions in Python are a special type of function that can be used to create iterators in a more concise and efficient way. Instead of returning a value and terminating the function, generator functions use the yield
statement to return a value and suspend the function, allowing it to be resumed later and continue generating values.
Here’s an example of a simple generator function in Python:
def count_up_to(n): i = 1 while i <= n: yield i i += 1
In this example, we define a generator function called count_up_to()
that takes an integer n
as input and generates the sequence of integers from 1 up to n
. The function uses a while
loop to generate each value in the sequence, and the yield
statement is used to return each value one at a time.
We can use the count_up_to()
generator function to generate a sequence of values like this:
my_generator = count_up_to(5) for item in my_generator: print(item)
In this example, we create a generator object by calling the count_up_to()
function with an input of 5. We then use the generator object in a for
loop to iterate over the sequence of values generated by the function.
The main advantage of using generator functions is that they allow you to generate large or infinite sequences of values without loading them all into memory at once. Because the yield
statement suspends the function and stores its state, the generator can be resumed later to generate more values as needed. This makes generator functions ideal for processing data in a streaming fashion, or for generating sequences on-the-fly based on user inputs or other dynamic factors.