Python Generators
Generators are special functions in Python that allow us to create an iterable sequence of values. Unlike normal functions, generators do not produce a single value upon execution. Instead, they produce a sequence of values as per the requirement. A simple for
loop can be used to iterate over the values.
Syntax
A generator function is defined with the use of yield
keyword. It helps to return the generator object created by the generator function. Here is the syntax for defining a generator function in Python.
def generator_function():
# some code
yield value
Example
Let's look at an example of a generator function that returns an iterable sequence of squares.
def generate_squares(n):
for num in range(n):
yield num**2
Output
To get output from a generator, we need to iterate over the generator object. Here is how we can do that for our generate_squares() function:
for i in generate_squares(5):
print(i)
The above code will output:
0
1
4
9
16
Explanation
As we can see in the generate_squares()
function, we have used the yield
keyword to return a sequence of squares. The function returns a generator object when called, which can be iterated using a for
loop. The loop runs until the generator sequence is exhausted.
The output is generated at runtime when we iterate over the generator object. This means we can generate a sequence of values without storing them in memory. This is very useful in cases where we have to generate an extremely large sequence of values and don't want to waste memory storing them.
Use
Generators are used in various scenarios where we need to generate a sequence of values dynamically. Some common use cases of generators are as follows:
- Processing large datasets that don't fit in memory
- Generating a stream of values dynamically
- Implementing infinite sequences that can't be stored in memory
Important Points
- Generator functions allow us to create iterable sequences of values.
- The
yield
keyword is used to return the generator object created by the generator function. - We can iterate over the generator object using a
for
loop to generate the output. - Generators are useful when we need to generate a sequence of values dynamically without storing them in memory.
Summary
In summary, generators are a powerful feature of Python that allows us to generate iterable sequences of values dynamically. They are useful in situations where we have to generate a large sequence of values without storing them in memory. The yield
keyword is used to create generator functions, and the resulting generator objects can be iterated over using a for
loop.