Command Palette

Search for a command to run...

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

Grouping, combinations and batches

batched needs Python 3.12 or later (the browser runs 3.13). The batches mimic splitting documents into groups for an embedding API.

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?

Grouping, combinations and batches Python 3.12+
Sign in to run this example in your browser.

Expected output

a ['apple', 'avocado']
b ['banana', 'blueberry']
c ['cherry']
pairwise:      [(1, 4), (4, 9), (9, 16)]
product:       [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
permutations:  [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
combinations:  [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
send to embedding API: ('d1', 'd2')
send to embedding API: ('d3', 'd4')
send to embedding API: ('d5',)