Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 10 / Topic 9 of 11

itertools highlights

itertools is a standard-library module of fast, lazy tools for working with iterables. Think of it as a set of conveyor-belt attachments: join belts, cut a belt, group items, add up as you go.

Tool What it does
count(start) endless numbers: start, start+1, โ€ฆ
islice(it, n) take the first n items (works on endless iterators)
chain(a, b) loop over a then b, as one
groupby(items, key=f) groups neighbouring items with the same f(item)
batched(items, n) chunks of size n (Python 3.12+)
accumulate(items) running totals
from itertools import accumulate, batched, chain, count, islice

print(list(islice(count(5001), 3)))           # [5001, 5002, 5003]
print(list(chain(["Asha"], ["Ravi", "Meera"])))  # ['Asha', 'Ravi', 'Meera']
print(list(batched("ABCDEFG", 3)))
# [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
print(list(accumulate([450, 1200, 800])))     # [450, 1650, 2450]

groupby: sort first!

groupby only groups items that are next to each other. Sort by the same key first, or one city can appear in several groups.

from itertools import groupby

sales = [("Pune", 450), ("Delhi", 800), ("Pune", 1200)]

print([city for city, _ in groupby(sales, key=lambda s: s[0])])
# ['Pune', 'Delhi', 'Pune'] <- Pune twice: not sorted

ordered = sorted(sales, key=lambda s: s[0])
for city, rows in groupby(ordered, key=lambda s: s[0]):
    print(city, sum(amount for _, amount in rows))

Output of the loop:

Delhi 800
Pune 1650

๐Ÿ” Going deeper: each group from groupby is itself a lazy iterator that is lost when you move to the next group, so use it (or list() it) inside the loop.

Full program: examples/05_itertools_tour.py.

Read more: the official itertools documentation - the whole page is worth a skim.

Done here? The practice set for Part 10 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide