Iteration Tools · 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 squares(n):
    for i in range(n):
        yield i * i

sq = squares(4)
print(max(sq), sum(sq))
2. What does this print?
print(any([]), all([]))
3. How many times does check get called?
calls = 0
def check(x):
    global calls
    calls += 1
    return x > 2

any(map(check, [1, 5, 2, 7, 3]))
print(calls)
4. What does this print?
from itertools import islice
it = iter(range(10))
a = list(islice(it, 3))
b = list(islice(it, 3))
print(a, b)
5. What does this print?
from itertools import takewhile, dropwhile
data = [1, 4, 6, 2, 8]
print(list(takewhile(lambda x: x < 5, data)),
      list(dropwhile(lambda x: x < 5, data)))
6. What does this print?
from itertools import repeat
rows = list(repeat([], 3))
rows[0].append('x')
print(rows)
7. You have a generator files() that lazily yields one open-file iterator per log file. Which expression iterates all their lines without forcing files() to produce every file up front?
8. What does this print?
from itertools import tee
source = iter([1, 2, 3, 4])
a, b = tee(source)
next(a)
next(source)
print(list(a), list(b))
9. What does this print?
from itertools import accumulate
import operator
print(list(accumulate([2, 3, 4], operator.mul, initial=1)))
10. What does this print?
from itertools import pairwise
print([b - a for a, b in pairwise([3, 7, 8, 5])])
11. What does this print?
from itertools import groupby
print([(k, len(list(g))) for k, g in groupby('aabccca')])
12. How many tuples does itertools.combinations('ABCD', 2) produce, compared to itertools.permutations('ABCD', 2)?

Coding exercises

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

Exercise 1: The first n matches, lazily

Write first_matches(iterable, predicate, n) that returns a list of the first n items of iterable for which predicate(item) is truthy.

It must work on infinite iterators (so it may not consume more than it needs), and if fewer than n items match, return all the matches. Try to solve it with filter and itertools.islice rather than a manual loop.

Hints (2)
  1. filter(predicate, iterable) is lazy: it produces matches one at a time.
  2. islice(something, n) stops after n items, so it never asks the filter for more.
Show a solution
from itertools import islice

def first_matches(iterable, predicate, n):
    return list(islice(filter(predicate, iterable), n))

Exercise 2: Round-robin interleaving

Write a generator function interleave(*iterables) that yields one item from each iterable in turn, skipping iterables that have run out, until all are exhausted.

For example, list(interleave('ABC', [1, 2], 'xyzw')) is ['A', 1, 'x', 'B', 2, 'y', 'C', 'z', 'w'].

Values like None or 0 inside the data must be kept. A neat approach combines zip_longest, a unique sentinel fillvalue, and chain.from_iterable.

Hints (3)
  1. zip stops at the shortest input; zip_longest keeps going and fills the gaps.
  2. Use missing = object() as the fillvalue so the filler can't be confused with real data such as None, then skip it with is not.
  3. chain.from_iterable(rounds) flattens the tuples into one stream.
Show a solution
from itertools import zip_longest, chain

def interleave(*iterables):
    missing = object()      # a sentinel no real data can be equal to
    rounds = zip_longest(*iterables, fillvalue=missing)
    for item in chain.from_iterable(rounds):
        if item is not missing:
            yield item

Exercise 3: Longest streak

Write longest_streak(iterable) that returns a tuple (value, length) describing the longest run of consecutive equal items. If several runs are equally long, return the first one. For an empty iterable, return None.

For example, longest_streak('HHTTTHTTTTH') is ('T', 4).

Hints (3)
  1. groupby without a key yields one (value, group) pair per run of equal neighbors.
  2. A group has no len, but sum(1 for _ in group) counts it.
  3. max(..., key=..., default=None) handles the empty case, and returns the first of several equal maxima.
Show a solution
from itertools import groupby

def longest_streak(iterable):
    runs = ((key, sum(1 for _ in group)) for key, group in groupby(iterable))
    return max(runs, key=lambda run: run[1], default=None)

Exercise 4: Sliding windows

Write windows(iterable, n) that lazily yields every run of n consecutive items as a tuple, like a generalized pairwise. For example, list(windows([1, 2, 3, 4, 5], 3)) is [(1, 2, 3), (2, 3, 4), (3, 4, 5)].

It must accept any iterable (including infinite iterators), and yield nothing if there are fewer than n items. One approach: tee the input n times, advance the k-th copy by k items with islice, then zip the copies.

Hints (3)
  1. tee(iterable, n) gives n independent iterators over the same data.
  2. islice(copy, k, None) skips the first k items of a copy, lazily.
  3. zip of the shifted copies stops when the most-advanced copy runs out, which is exactly when the last full window has been produced.
Show a solution
from itertools import tee, islice

def windows(iterable, n):
    copies = tee(iterable, n)
    shifted = (islice(copy, k, None) for k, copy in enumerate(copies))
    return zip(*shifted)