Generators and Yield

intermediate level · ~20 min · Module 12: Iterators & Generators

Produce values lazily without storing entire datasets in memory.

Learning objectives

  • Differentiate between iterables, iterators, and generators
  • Create memory-efficient generator functions using yield

Lesson material

Yield vs Return

Functions with yield return a generator object that evaluates values on demand when iterated.

Example code

def countdown(n):
    while n > 0:
        yield n
        n -= 1

gen = countdown(3)
for num in gen:
    print(num, end=" ")
print()

Practice exercise: Fibonacci Generator

Write a generator function `fib(n)` yielding the first `n` numbers of Fibonacci sequence (starting 0, 1). Print all items generated for `fib(5)`.

Test yourself with the Module 12: Iterators & Generators quiz →

View the full Python curriculum →