Generators · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
def gen():
    print('start')
    yield 1

g = gen()
print(type(g).__name__)
2. What does this print?
def f():
    print('a')
    yield 1
    print('b')
    yield 2

g = f()
print(next(g))
print(next(g))
3. What does this print?
g = (c.upper() for c in 'abc')
print(list(g), list(g))
4. What does this print?
def gen():
    yield 1
    return 'done'

g = gen()
next(g)
try:
    next(g)
except StopIteration as ex:
    print(ex.value)
5. What does this print?
def squares(n):
    for i in range(n):
        yield i * i

g = squares(4)
print(iter(g) is g, '__next__' in dir(g))
6. What does this print?
n = 2
g = (i * n for i in range(3))
n = 10
print(list(g))
7. What does this print?
def squares(n):
    for i in range(n):
        yield i * i

sq = squares(5)
e = enumerate(sq)
next(sq)
print(next(e))
8. What does this print?
class Evens:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        for i in range(0, self.n, 2):
            yield i

e = Evens(5)
print(list(e), list(e))
9. What does this print?
def inner():
    yield 'a'
    return 'inner result'

def outer():
    r = yield from inner()
    yield r

print(list(outer()))
10. Which of these lines is a SyntaxError?
11. A class defines __iter__ (as a generator) but neither __reversed__ nor __len__/__getitem__. What does reversed(obj) do?
12. You build a large nested data set with generator expressions and then iterate over every element. Compared with nested list comprehensions, what do you usually gain?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: A correct Fibonacci generator

Write a generator function fib_gen(n) that yields the first n Fibonacci numbers 1, 1, 2, 3, 5, 8, … (each number is the sum of the two before it).

It must work for every n >= 0: fib_gen(0) yields nothing and fib_gen(1) yields just 1. The starter is the version from the lesson, which is wrong for small n.

It must be lazy: never compute more numbers than have been requested, and never recompute earlier numbers from scratch.

Hints (2)
  1. Instead of yielding two values before the loop, run the loop exactly n times and yield one value per iteration.
  2. Yield a first, then slide the pair forward: a, b = b, a + b.
Show a solution
def fib_gen(n):
    a, b = 1, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

Exercise 2: A re-usable, reversible countdown

Write a class Countdown so that Countdown(start) is an iterable (not an iterator):

- iterating it yields start, start - 1, …, 1 - it can be iterated any number of times - reversed(Countdown(start)) yields 1, 2, …, start

Use generators for both directions; don't store a list of the numbers.

Hints (3)
  1. Store only start. State that changes during iteration belongs in the generator, not on self.
  2. Put yield directly inside __iter__. Each call then returns a fresh generator.
  3. reversed() looks for a __reversed__ method; write it the same way.
Show a solution
class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        for i in range(self.start, 0, -1):
            yield i

    def __reversed__(self):
        for i in range(1, self.start + 1):
            yield i

Exercise 3: Flatten any nesting, lazily

Write a generator function flatten(obj) that yields the "leaf" values of arbitrarily nested iterables, in order.

- Any iterable (lists, tuples, sets, ranges, generators, …) is flattened recursively. - Strings and bytes are leaves, not containers: 'abc' is yielded as 'abc', not as 'a', 'b', 'c'. - Anything that isn't iterable (numbers, None, …) is a leaf. - If obj itself is a leaf (for example flatten(42) or flatten('hi')), yield it as the only value.

Use yield from for the recursion.

Hints (3)
  1. Make flatten handle a single object: if it's a leaf, yield it and return; otherwise loop over it and yield from flatten(item) for each item.
  2. To test whether something is iterable, try iter(obj) and catch TypeError.
  3. Check for str/bytes before trying iter(), otherwise a one-character string would recurse forever.
Show a solution
def flatten(obj):
    if isinstance(obj, (str, bytes)):
        yield obj
        return
    try:
        items = iter(obj)
    except TypeError:
        yield obj        # not iterable: a leaf
        return
    for item in items:
        yield from flatten(item)

Exercise 4: Chain the brand files

The files car-brands-1.txt, car-brands-2.txt and car-brands-3.txt (UTF-8) contain one car brand per line.

1. Write a generator clean_lines(file_name) that opens one file and yields each line with surrounding whitespace removed, skipping lines that are empty after stripping. 2. Write a generator brands(*file_names) that yields the cleaned lines of every file, in order, using yield from clean_lines(...).

Both must be lazy: a file must not be opened until iteration actually reaches it.

Hints (2)
  1. In clean_lines, keep the with block and replace the list with a loop that yields each stripped, non-empty line.
  2. brands needs only two lines: loop over the names and yield from clean_lines(name).
Show a solution
def clean_lines(file_name):
    with open(file_name, encoding='utf-8') as f:
        for line in f:
            cleaned = line.strip()
            if cleaned:
                yield cleaned

def brands(*file_names):
    for name in file_names:
        yield from clean_lines(name)