Python Generators

A generator produces values one at a time instead of creating the entire collection in memory. This makes generators useful for processing large amounts of data.

Using yield

The yield keyword turns a normal function into a generator function.

Python
Generate numbers one at a time.
def numbers():
    yield 1
    yield 2
    yield 3

for number in numbers():
    print(number)

Using next()

The next() function retrieves the next value from a generator.

Python
Read generator values one by one.
def count():
    yield 10
    yield 20
    yield 30

generator = count()

print(next(generator))
print(next(generator))
print(next(generator))

Generator Expressions

Generator expressions use syntax similar to list comprehensions but produce values lazily.

Python
Create a generator expression.
squares = (x * x for x in range(5))

for value in squares:
    print(value)

Memory Efficiency

A list stores all generated values, while a generator produces each value when needed.

Python
Compare a list with a generator.
numbers_list = [x * x for x in range(1000000)]
numbers_generator = (x * x for x in range(1000000))

Common Use Cases

Generators are useful for large files, data processing pipelines, streaming data, infinite sequences, and other situations where values can be processed one at a time.

Summary

Python generators use yield to produce values lazily. They can reduce memory usage and are especially useful when processing large or continuously generated data.