Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.4 — itertools
Python · Example 3 of 3

A realistic groupby: totals per customer

Orders arrive in any order, as they would from an API or a log. Without sorting, groupby splits each customer into several groups. Sorting by the same key first fixes it. operator.itemgetter("customer") is a ready-made function that fetches that key from each dictionary.

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.

01

Use islice and count to print the first five multiples of 7 as a list.

02

Use accumulate to turn the daily sales [5, 3, 8, 2] into running totals and print them.

03

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?)

04

Use pairwise to print the differences between neighbours of [2, 5, 9, 14].

Explain it without notes

01

What does itertools.groupby do, and what must you do to the data first?

02

Why are the itertools tools lazy, and what are the consequences?

03

What is the difference between permutations and combinations? Give the result of each for "abc" taken 2 at a time.

04

Why would you use batched in an AI application?

05

You call list(islice(it, 3)) twice on the same iterator it. What do you get, and why?

A realistic groupby: totals per customer
Sign in to run this example in your browser.

Expected output

unsorted groups: ['Meera', 'Ravi', 'Meera', 'Ravi', 'Asha']
Asha: 1 orders, total 300
Meera: 2 orders, total 370
Ravi: 2 orders, total 130