What is generator in python with examples?

In Python programming, a generator is a special type of function that can be paused and resumed. It allows you to generate a sequence of values on the fly, without having to store them all in memory at once. Generators are useful when you need to iterate over a large set of data or generate an infinite sequence.

https://python-reference.readthedocs.io/en/latest/docs/generator/

Here’s an example of a generator function in Python:

def count_up_to(n):
    i = 0
    while i <= n:
        yield i
        i += 1

# Using the generator
for num in count_up_to(5):
    print(num)

In this example, the count_up_to function is a generator that generates numbers from 0 up to a specified value n. The yield keyword is used to pause the function and return a value, and the function can be resumed from where it left off. The for loop demonstrates how you can iterate over the values generated by the generator.

When you run the code, it will output:

0
1
2
3
4
5

Each number is generated one at a time, and the generator function keeps track of its internal state, allowing you to iterate over the sequence without needing to store all the numbers in memory simultaneously.

Leave a Reply

Your email address will not be published. Required fields are marked *