Python Generators · Exercises
Core Python

Python Generators Exercises

4 exercises that build on the Python Generators, Iterators and yield lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A generator is a function that uses yield to hand out values one at a time, pausing after each one and resuming where it left off when the next value is requested. By the end you can explain iterables and iterators, use iter() and next(), write a generator function with yield, use generator expressions, and say when a generator saves memory. You will practise: Your first generator; Predict the pauses; Fix the average; A lazy running total.

0 / 4 completed

Python Generators practice exercises

1. Your first generator

Write code Easy

Write a generator function count_up(limit) that yields the numbers 1, 2, 3, … up to and including limit. For example list(count_up(3)) is [1, 2, 3]. Use yield, not a list.

Your code
def count_up(limit):
    # yield 1, 2, ..., limit
    pass

for n in count_up(3):
    print(n)

2. Predict the pauses

Predict the output Medium

Read the code and type exactly what it will print. Think about when the body of letters() actually runs. Then press Check to compare.

Read this code
def letters():
    print("start")
    yield "a"
    print("middle")
    yield "b"
    print("end")

gen = letters()
print("created")
print(next(gen))
print(next(gen))
print(list(gen))

3. Fix the average

Fix the bug Medium

This code should take 5 off every price and print Average discounted price: 25.0, but it crashes with ZeroDivisionError. Find out why count is 0 and fix the code. Keep the variable names.

Your code
prices = [25, 45, 20]
discounted = (p - 5 for p in prices)

total = sum(discounted)
count = len(list(discounted))
average = total / count
print("Average discounted price:", average)

4. A lazy running total

Write code Hard

Write a generator function running_total(numbers) that yields the running sum: for [5, 3, 2] it yields 5, 8, 10. It must work with any iterable, including another generator, and it must be lazy: read one number, yield one total. Don't build a list first.

Your code
def running_total(numbers):
    # keep a total, and yield it after adding each number
    pass

print(list(running_total([5, 3, 2])))

Next lessonPython Iterators

More Python Generators, Iterators and yield examples · All Python exercises