Generator
In one line
A generator is a function that produces values lazily using yield, pausing between each value until the next is requested.
In simple words
A generator is a function that uses yield to produce values one at a time. Instead of computing all values and returning them at once (like a list), a generator computes each value on demand, pausing between yields.
This makes generators memory-efficient — you can process infinite sequences or huge datasets without loading everything into memory. When you call a generator function, it returns a generator object (an iterator), not the values themselves.
Each call to next() (or each iteration in a for loop) resumes the generator, runs until the next yield, and produces that value. When the function ends, StopIteration is raised automatically.
Example
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(8):
print(next(fib), end=" ")
# Output: 0 1 1 2 3 5 8 13Generators use yield to produce values lazily. This fibonacci generator is infinite but only computes values as requested.
Common confusions
Confused with: list
The difference: A list stores all values in memory at once. A generator produces values one at a time on demand. Generators are memory-efficient but can only be iterated once (use list() to collect all values if needed).
Related terms
Related Resources
Related Lessons
- Generators
Generators in Python.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.