Skip to content

Generators & yield

Python

Master generators: lazy evaluation, yield, and generator pipelines.

Official Site
01

Overview

Generators produce values lazily with yield. Memory-efficient for large sequences. Generator pipelines: compose with map/filter. yield from delegates to sub-generator. Infinite generators possible. One-shot: cannot reuse.

bash
def fib():
  a,b=0,1
  while True:
    yield a; a,b=b,a+b

gen=fib()
next(gen); next(gen)  # 0, 1

# Pipeline
def squares(it): yield from (x**2 for x in it)
def evens(it): yield from (x for x in it if x%2==0)
result=list(evens(squares(range(100))))
02

Best Practices

Use generators for large/infinite sequences. yield from for delegation. Compose generators in pipelines. Cannot reuse (create new). Use itertools for common patterns. Use send() for coroutines. Prefer generator expressions for simple cases.)

Ready to try Generators & yield?

Visit the official site for the latest version and full documentation.

Visit Generators & yield