Generators
Understand generators and their use for creating iterators.
1
Introduction to Generators
Generators are a special type of iterator in Python that allow you to iterate over data lazily. Instead of returning all the data at once, they yield one item at a time, making them memory-efficient.
In this lesson, you’ll learn how to create and use generators in Python.

2
What Is a Generator?
A generator is a function that uses the yield keyword to return values one at a time. Each call to the generator’s next() method resumes execution from where it last yielded.
# Basic generator example
def my_generator():
yield 1
yield 2
yield 3
# Using the generator
gen = my_generator()
print(next(gen)) # Outputs: 1
print(next(gen)) # Outputs: 2
print(next(gen)) # Outputs: 3