Generators in Python
Generators are a way to create iterators in Python. Here's an example of defining a simple generator:
python
def my_generator(n):
for i in range(n):
yield i
for i in my_generator(5):
print(i)
In this example, we define a generator function called my_generator. The function takes an argument n and uses a for loop to yield a value for each iteration. When we use the generator in a for loop, the yield statement returns the next value in the sequence.
When we run the loop, it will print the numbers 0 to 4, which were generated by the my_generator function.
No comments:
Post a Comment