Account
Categories

Generator and Its Uses


Definition:

A generator is a function that gives one value at a time using yield.

After giving one value, it pauses and resumes when called again until all values are returned.

Generators work only inside a function because yield can be used only inside a function.

Syntax:

def my_generator():
    yield value

Example:

def numbers():
    for i in range(1, 3):
        yield i

for num in numbers():
    print(num)

Output:

1
2

Why Use Generators?

  • It returns one value at a time using yield, saving memory.
  • It improves performance by not storing all values at once.
  • It can easily process big datasets.
  • Generators are very useful and recommended to use.