Python itertools · Exercises
Core Python

Python itertools Exercises

4 exercises that build on the Python itertools 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: itertools is a standard-library toolbox of fast, lazy iterator building blocks for chaining, slicing, grouping, combining and accumulating values without building big lists. By the end you can pick the right itertools tool for a job, limit endless iterators, build combinations and running totals, group sorted records, and avoid the one-pass iterator traps. You will practise: Every outfit; Predict the stream; Fix the match list; Run-length encoding.

0 / 4 completed

Python itertools practice exercises

1. Every outfit

Write code Easy

Write a function all_outfits(shirts, pants) that returns a list containing every (shirt, pants) pair, shirts first. Use itertools.product. The program then prints how many outfits there are for the lists in the starter code.

Your code
from itertools import product

def all_outfits(shirts, pants):
    # return a list of (shirt, pants) tuples
    pass

outfits = all_outfits(["white", "blue"], ["jeans", "shorts", "chinos"])
print(len(outfits))

2. Predict the stream

Predict the output Easy

Read the code and type exactly what it prints. Watch what next() and list() use up. Then press Check.

Read this code
from itertools import chain, islice, accumulate

a = [1, 2]
b = [3, 4, 5]
stream = chain(a, b)
print(next(stream), next(stream))
print(list(stream))
print(list(stream))
print(list(accumulate(b)))
print(list(islice(chain(a, b), 1, 4)))

3. Fix the match list

Fix the bug Medium

match_list(team) should return how many matches there are (every pair of players meets once) and a list of lines such as "Asha vs Ben". It reports the right count but the list of lines is empty. Fix the bug.

Your code
from itertools import combinations

def match_list(team):
    matches = combinations(team, 2)
    count = len(list(matches))
    lines = [f"{a} vs {b}" for a, b in matches]
    return count, lines

count, lines = match_list(["Asha", "Ben", "Chen"])
print(count)
print(lines)

4. Run-length encoding

Write code Hard

Write rle(text) that compresses each run of the same character into the character followed by the run length: "aaabcc" becomes "a3b1c2". Use itertools.groupby directly on the text and do not sort it: groupby only groups neighbours, which is exactly what a run is. The empty string gives "". Print rle("aaabcc").

Your code
from itertools import groupby

def rle(text):
    # build a string such as "a3b1c2" from the runs of equal characters
    return ""

print(rle("aaabcc"))

Next lessonPython File Handling

More Python itertools examples · All Python exercises