Generators in Python

 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

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...