01 / 20

Generator Functions
yield

Learn to write lazy, memory-efficient Python functions that produce values one at a time using the yield keyword.

Python

What Is a Generator?

A generator is a special kind of function that returns an iterator. Instead of computing all values at once and storing them in memory, a generator produces values one at a time, pausing between each one.

Any function that contains the keyword yield (instead of or alongside return) is automatically a generator function.

Why Generators Matter

Memory Efficient
Generate values on the fly instead of building an entire list. Process millions of items with almost zero memory overhead.
Lazy Evaluation
Values are computed only when requested. If you only need the first 5 items from a billion, only 5 are ever created.
Clean Pipelines
Chain generators together to build elegant data-processing pipelines, keeping each step simple and composable.

yield vs return

return Call function Compute ALL values Return list, end function Memory: all at once yield Call function Compute ONE value Yield it, PAUSE (state preserved) Memory: one at a time

The Core Rule

def my_generator(): yield "first" yield "second" yield "third"
gen = my_generator() # No output yet! print(next(gen)) # "first" print(next(gen)) # "second" print(next(gen)) # "third"

The Generator Protocol

Caller Generator next(gen) yield value When exhausted: raises StopIteration repeats for each yield

Generator vs List

Generator List
Memory \(O(1)\): one item at a time \(O(n)\): all items stored
Evaluation Lazy (on demand) Eager (all at once)
Reusable? No: single pass only Yes: iterate many times
Indexing No: sequential access Yes: random access
Syntax yield or ( ... ) return or [ ... ]

How to Write a Generator

1
Define a function using def, just like a normal function.
2
Use yield (instead of return) to produce each value. You can have multiple yield statements or yield inside a loop.
3
Call the function to get a generator object. No code runs yet.
4
Consume values with next(), a for loop, or pass to list() / sum() / etc.

Example 1: Countdown

def countdown(n): while n > 0: yield n n -= 1 for num in countdown(5): print(num)

Example 2: Fibonacci Sequence

def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
fib = fibonacci() for _ in range(8): print(next(fib), end=" ") # 0 1 1 2 3 5 8 13

Example 3: Generator Expressions

Python offers a shorthand for simple generators that mirrors list comprehension syntax, using parentheses instead of brackets.

# List comprehension: builds entire list squares_list = [x**2 for x in range(1_000_000)] # Generator expression: produces one at a time squares_gen = (x**2 for x in range(1_000_000))
[ ... ]
List comp: stores 1 million ints in memory all at once.
( ... )
Gen expr: yields each square on demand. Almost zero memory.

Chaining Generator Pipelines

def evens(nums): for n in nums: if n % 2 == 0: yield n def doubled(nums): for n in nums: yield n * 2 data = range(1, 11) pipeline = doubled(evens(data)) print(list(pipeline)) # [4, 8, 12, 16, 20]

Delegating with yield from

yield from lets one generator delegate to another, forwarding all yielded values automatically.

def flatten(nested): for sublist in nested: yield from sublist data = [[1, 2], [3, 4], [5]] print(list(flatten(data))) # [1, 2, 3, 4, 5]

State Preservation

next() run code yield 1 pause next() resume yield 2 pause next() resume Stop end locals saved locals saved Generator Lifecycle Timeline

Common Mistakes

✕ Calling Instead of Iterating
Writing my_gen() in a print statement. That returns a generator object, not a value. Use next() or a for loop.
✕ Reusing an Exhausted Generator
Generators are single-use. Once exhausted, calling next() raises StopIteration. Create a new generator object to iterate again.
✕ Using return with a Value
Placing return some_value inside a generator does not yield it. The value becomes the StopIteration exception's argument, which is almost never useful.

Quick Reference Summary

Concept Syntax / Detail
Define generator def func(): yield value
Create object gen = func()
Get next value next(gen)
Iterate all for x in gen: ...
Delegate yield from iterable
Gen expression (expr for x in iterable)
Exhaustion Raises StopIteration

Question 1 of 5

What does calling a generator function (e.g., my_gen()) return?

Question 2 of 5

What happens when you call next() on a generator that has no more yield statements to execute?

Question 3 of 5

What is the value of result?

Question 4 of 5

Which syntax creates a generator expression?

Question 5 of 5

What does Line B print?