Counting, chaining and running totals
Change the step in count(10, 5) and the function passed to accumulate (try min, or operator.mul after importing operator).
itertools is the standard library's toolbox for iterators: infinite counters, chaining, slicing, grouping, combinations, running totals, and splitting into batches. Every tool is lazy and works on any iterable.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use islice and count to print the first five multiples of 7 as a list.
Use accumulate to turn the daily sales [5, 3, 8, 2] into running totals and print them.
Group the words ["ant", "ape", "bee", "bat", "cow"] by first letter and print each letter with the number of words. (Hint: are the words sorted by first letter?)
Use pairwise to print the differences between neighbours of [2, 5, 9, 14].
Explain it without notes
What does itertools.groupby do, and what must you do to the data first?
Why are the itertools tools lazy, and what are the consequences?
What is the difference between permutations and combinations? Give the result of each for "abc" taken 2 at a time.
Why would you use batched in an AI application?
You call list(islice(it, 3)) twice on the same iterator it. What do you get, and why?
Expected output
count: [10, 15, 20, 25]
cycle: ['A', 'B', 'A', 'B', 'A']
repeat: ['hi', 'hi', 'hi']
chain: [1, 2, 3, 'a', 'b']
accumulate: [1, 3, 6, 10]
running max: [3, 3, 4, 4, 5]
islice slice: [2, 5, 8]