Skip to content

Generators and Iterators in Python

Use generators and the yield keyword to write memory-efficient, lazy Python code.

Generators produce values on demand instead of building a full list in memory.

The yield keyword

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for num in count_up_to(5):
    print(num)

Why it matters

  • Memory efficient — process one item at a time.
  • Lazy — work only happens when you ask for the next value.
  • Composable — chain generators like filter and map pipelines.
squares = (x * x for x in range(10))  # generator expression
AdSense — in-article slot

Related Reading