yieldIntermediate Examples

Pauses a generator function and produces a value to the caller

Yield for memory-efficient processing

Processing large data without loading it all into memory.

python
def read_chunks(data, chunk_size):
    for i in range(0, len(data), chunk_size):
        yield data[i:i + chunk_size]

data = list(range(100))
for chunk in read_chunks(data, 15):
    print(f"Processing chunk of {len(chunk)}: sum={sum(chunk)}")

# Generator expressions (like list comp but lazy)
total = sum(x**2 for x in range(1_000_000))
print(f"Sum of squares: {total}")

# Chaining generators
def evens(source):
    for x in source:
        if x % 2 == 0:
            yield x

def doubled(source):
    for x in source:
        yield x * 2

pipeline = doubled(evens(range(10)))
print(list(pipeline))

Generators process one item at a time, using constant memory regardless of data size. Chain them to build data processing pipelines.

Want to try these examples interactively?

Open Intermediate Playground