Python Generators

 

Python Generators

Definition

A generator in Python is a function that produces values one at a time using the yield keyword. It pauses after each value and can resume later, making it memory-efficient for handling large datasets.


Syntax:

def generator_function():
    yield value

Example:

def my_generator():
    yield 1  # Pause and return 1
    yield 2  # Pause and return 2
    yield 3  # Pause and return 3

# Using the generator
gen = my_generator()  # Create a generator object

print(next(gen))  # Resume generator and get the next value: 1
print(next(gen))  # Resume generator and get the next value: 2
print(next(gen))  # Resume generator and get the next value: 3

Output:

1
2
3

Post a Comment

0 Comments