What are the generators in python?

Generators are a type of iterable, like lists or tuples, that allow you to iterate over their elements one at a time. However, unlike lists and tuples, generators do not store all of their elements in memory at once. This can be useful when working with large datasets that you don't want to load into memory all at once.

Here's an example of a generator function that yields the numbers from 1 to n:

def numbers_up_to(n):
    for i in range(1, n+1):
        yield i

for i in numbers_up_to(5):
    print(i)


 

This will output the numbers 1 through 5.

One of the main benefits of generators is that they allow you to iterate over large datasets without consuming a lot of memory. For example, if you had a dataset with 10 million rows and you wanted to process each row one at a time, you could use a generator function to read in and yield one row at a time, rather than reading in the entire dataset and storing it in a list or tuple.

Generators are also useful for creating infinite sequences, such as an infinite stream of random numbers. Here's an example of a generator that yields an infinite stream of random numbers:

    import random

    def infinite_random_numbers():
        while True:
            yield random.random()

    for i in infinite_random_numbers():
        print(i)


This generator function will continue to yield random numbers indefinitely, unless you break out of the loop manually.

Overall, generators are a useful tool for working with large datasets and infinite sequences in Python, allowing you to iterate over the data one element at a time while conserving memory.

 

No comments

Powered by Blogger.