← All lessons

Generators: yield

Sign in · Sign up

Lesson 11.1

A generator doesn't keep all the values at once: it gives them out on demand. You write yield inside a function:

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        ...                 # give out a and move the pair

yield gives out a value and freezes until the next request. A return in its place would return one value and end the function. A generator can be looped over only once — after the end it is used up.

Write fib(n) with yield: the first n Fibonacci numbers, starting with 0. The check collects a list from your generator.

Hint

A generator is a function with yield instead of return.

Keep two numbers (a and b): give out a, then move the pair forward. for _ in range(n) limits the number of values to exactly n.