Skip to the content

Generators with yield

Python · Unit 15: Comprehensions and generators

A function with yield instead of return is a generator: rather than one result, it hands back many, one at a time.

Calling it doesn't run the body yet. With list() you ask for every value at once.

def count(n):
    for i in range(n):
        yield i

print(list(count(3)))

Prints

[0, 1, 2]

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so the function hands back the even numbers.

  3. 3. Predict the output

    What does this code print?

  4. 4. Put the lines in order

    Put the lines in order to build a generator of the odd numbers under n.

  5. 5. Find the bug

    It should hand back the square of each number, from 0 to n minus 1. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank to keep the first three values of the generator.

  8. 8. Multiple choice

    naturals() never ends. Why doesn't the program hang?

  9. 9. Predict the output

    What does this code print?

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →