Exercises - itertools
Chaining and Filtering
Section titled βChaining and FilteringβExercise 1 β π’ Beginner
Use chain to flatten a list of lists into a single list without using a loop or list comprehension.
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9]Exercise 2 β π’ Beginner
Use compress to select only the items marked as available from a product catalogue.
products = ["apple", "banana", "cherry", "date", "elderberry"]available = [1, 0, 1, 1, 0]
# expected output: ['apple', 'cherry', 'date']Exercise 3 β π’ Beginner
Use takewhile and dropwhile to split a list of sensor readings into two parts β the stable readings before the first spike, and everything from the spike onwards.
readings = [10, 11, 10, 12, 45, 11, 10, 13]# a spike is any reading above 20
# expected:# stable β [10, 11, 10, 12]# spike β [45, 11, 10, 13]Exercise 4 β π‘ Intermediate
Use chain.from_iterable to lazily flatten a deeply irregular list of lists, then filter only even numbers from the result.
data = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
# expected output: [2, 4, 6, 8, 10]Transformation
Section titled βTransformationβExercise 5 β π’ Beginner
Use starmap to compute the area of a list of rectangles, where each rectangle is represented as a (width, height) tuple.
rectangles = [(3, 4), (5, 6), (2, 8), (7, 1)]
# expected output: [12, 30, 16, 7]Exercise 6 β π’ Beginner
Use accumulate to compute the running total of a list of daily sales figures.
daily_sales = [120, 340, 80, 560, 230, 410]
# expected output: [120, 460, 540, 1100, 1330, 1740]Exercise 7 β π‘ Intermediate
Use starmap to apply a list of discount rates to a list of prices, where each pair is (price, discount_rate).
items = [(100, 0.10), (250, 0.20), (80, 0.05), (320, 0.15)]# discount formula: price * (1 - rate)
# expected output: [90.0, 200.0, 76.0, 272.0]Exercise 8 β π‘ Intermediate
Use accumulate with a custom function to compute the running maximum of a list of temperatures.
temperatures = [18, 22, 19, 25, 21, 27, 24]
# expected output: [18, 22, 22, 25, 25, 27, 27]# hint: accumulate accepts a binary function as second argumentGrouping
Section titled βGroupingβExercise 9 β π’ Beginner
Use zip_longest to pair up two lists of different lengths β a list of students and a list of grades β filling missing grades with "N/A".
students = ["Alice", "Bob", "Charlie", "Diana", "Eve"]grades = [85, 92, 78]
# expected output:# [('Alice', 85), ('Bob', 92), ('Charlie', 78), ('Diana', 'N/A'), ('Eve', 'N/A')]Exercise 10 β π‘ Intermediate
Use groupby to group a list of transactions by their status, then count how many transactions are in each group.
transactions = [ {"id": 1, "status": "pending", "amount": 100}, {"id": 2, "status": "pending", "amount": 250}, {"id": 3, "status": "completed", "amount": 175}, {"id": 4, "status": "completed", "amount": 300}, {"id": 5, "status": "failed", "amount": 50}, {"id": 6, "status": "completed", "amount": 225},]
# expected output:# pending: 2 transactions# completed: 3 transactions# failed: 1 transactionExercise 11 β π‘ Intermediate
Use groupby to group a list of log entries by level, then collect all messages for each level into a list.
logs = [ {"level": "INFO", "message": "Server started"}, {"level": "INFO", "message": "Request received"}, {"level": "ERROR", "message": "Connection refused"}, {"level": "ERROR", "message": "Timeout exceeded"}, {"level": "WARN", "message": "Memory above 80%"}, {"level": "INFO", "message": "Request completed"},]
# expected output:# INFO: ['Server started', 'Request received', 'Request completed']# ERROR: ['Connection refused', 'Timeout exceeded']# WARN: ['Memory above 80%']Combinatorics
Section titled βCombinatoricsβExercise 12 β π’ Beginner
Use combinations to generate all possible pairs of players for a round-robin tournament.
players = ["Alice", "Bob", "Charlie", "Diana"]
# expected output:# [('Alice', 'Bob'), ('Alice', 'Charlie'), ('Alice', 'Diana'),# ('Bob', 'Charlie'), ('Bob', 'Diana'), ('Charlie', 'Diana')]# total: 6 matchesExercise 13 β π‘ Intermediate
Use permutations to generate all possible podium finishes (1st, 2nd, 3rd) from a list of competitors.
competitors = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
# expected:# total number of podium arrangements β 60# first 3 arrangements β# [('Alice', 'Bob', 'Charlie'),# ('Alice', 'Bob', 'Diana'),# ('Alice', 'Bob', 'Eve')]Exercise 14 β π‘ Intermediate
Use product to generate all possible combinations of size, colour, and material for a product catalogue.
sizes = ["S", "M", "L"]colours = ["red", "blue"]materials = ["cotton", "polyester"]
# expected: 12 combinations total# first 3:# [('S', 'red', 'cotton'),# ('S', 'red', 'polyester'),# ('S', 'blue', 'cotton'), ...]Combined Exercises
Section titled βCombined ExercisesβExercise 15 β π‘ Intermediate
Use chain, compress, and accumulate together to process a mixed dataset β flatten it, keep only positive numbers, then compute the running total.
data = [[3, -1, 4], [-2, 5, 6], [-3, 2, -4]]
# expected steps:# 1. flatten β [3, -1, 4, -2, 5, 6, -3, 2, -4]# 2. keep positives β [3, 4, 5, 6, 2]# 3. running total β [3, 7, 12, 18, 20]Exercise 16 β π΄ Advanced
Use groupby and accumulate together to compute the running total of sales per department.
sales = [ {"dept": "Eng", "amount": 100}, {"dept": "Eng", "amount": 250}, {"dept": "Eng", "amount": 175}, {"dept": "HR", "amount": 80}, {"dept": "HR", "amount": 120}, {"dept": "Finance", "amount": 300}, {"dept": "Finance", "amount": 150}, {"dept": "Finance", "amount": 200},]
# expected output:# Eng: [100, 350, 525]# HR: [80, 200]# Finance: [300, 450, 650]Exercise 17 β π΄ Advanced
Use combinations and starmap together to compute the distance between every pair of points in a list.
import math
points = [(0, 0), (3, 4), (6, 8), (1, 1)]
# expected output (rounded to 2 decimal places):# ((0,0), (3,4)) β 5.0# ((0,0), (6,8)) β 10.0# ((0,0), (1,1)) β 1.41# ((3,4), (6,8)) β 5.0# ((3,4), (1,1)) β 3.61# ((6,8), (1,1)) β 8.6Try solving each exercise using only itertools functions β resist reaching for explicit loops where a chain of iterator operations would express the intent more clearly.