Generator

A function that produces a sequence of values lazily, one at a time, using yield instead of return.

A generator is a function that uses yield instead of return. Each yield hands back one value and pauses the function, keeping its variables; the next request resumes it right where it left off. So a generator produces a sequence one item at a time rather than building the whole thing up front.

That makes generators lazy (nothing runs until you iterate) and great for streaming large files or long sequences with very little memory. They’re also a kind of iterator, and they’re one-shot: once consumed, you make a new one to iterate again.

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

for number in count_up_to(3):
    print(number)
Output
1
2
3

Where this shows up in real Python

Generators stream values one at a time, so you can process a huge file or an endless sequence without loading it all into memory.

Commonly used Generator tools

  • yield value — hand back one value and pause
  • next(gen) — pull the next value
  • (x for x in seq) — a generator expression
  • import itertools — ready-made generator building blocks

Official documentation: Python Tutorial: Generators

Related terms