This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python itertools, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does count(5) produce?
Answer: An infinite sequence starting at 5
Why: count is lazy and infinite; islice or zip is needed to bound it.
What does chain do?
Answer: Joins iterables end to end
Why: chain reads one iterable after another as a single stream.
What does list(islice(count(0), 3)) produce?
Answer: [0, 1, 2]
Why: islice takes the first three values from the infinite count stream.
What must you do before groupby if equal keys are scattered?
Answer: Sort the data
Why: groupby only groups adjacent items, so sort first when equal keys are not consecutive.
Complete the function that joins two iterables.
from itertools import chain
print(list(____([1], [2])))Answer: chain
Why: chain reads the first iterable, then the second.
Complete the function that bounds the infinite count.
from itertools import count, islice
print(list(____(count(1), 2)))Answer: islice
Why: islice takes a fixed number of values from an iterable.
Complete the function that groups adjacent values.
from itertools import groupby
data = [1, 1, 2]
for key, group in ____(data):
print(key, len(list(group)))Answer: groupby
Why: groupby groups consecutive items that share a key.
Complete the import for joining two lists.
from itertools import ____
print(list(chain([1], [2])))Answer: chain
Why: The chain function is imported from itertools.
What does the program output?
from itertools import count, islice
print(list(islice(count(3), 2)))Answer: [3, 4]
Why: The stream starts at three, and islice takes two values.
What appears on the screen?
from itertools import chain
print(list(chain("ab", "cd")))Answer: ['a', 'b', 'c', 'd']
Why: chain joins the two strings into one stream of characters.
What is printed?
from itertools import chain
print(list(chain([1], [2, 3])))Answer: [1, 2, 3]
Why: chain reads the first list and then the second list.
What is the output?
from itertools import groupby
data = [1, 1, 2]
print([(k, len(list(g))) for k, g in groupby(data)])Answer: [(1, 2), (2, 1)]
Why: The first group has two ones and the second group has one two.
Try the questions first
Open the practice page for Python itertools and answer the same 12 questions with instant feedback.