L3·Functions & Modules

🛠️functools & itertools

partial, reduce, lru_cache, chain, groupby, combinations.

functoolsitertoolsreducepartialpermutations

§ 1functools

partial pre-fills arguments, reduce folds a sequence into one value, lru_cache/cache memoize, wraps preserves metadata in decorators.

1from functools import partial, reduce​
2pow2 = partial(pow, exp=2)​
3print(pow2(5)) # 25​
4print(reduce(lambda a, b: a * b, [1, 2, 3, 4])) # 24​

§ 2itertools — infinite

count, cycle, repeat produce endless streams; combine with islice to take a few.

§ 3itertools — combinatorics

product, permutations, combinations generate arrangements lazily — great for brute-force interview answers.

1from itertools import combinations​
2print(list(combinations("abc", 2)))​

§ 4itertools — grouping

chain joins iterables, groupby groups consecutive equal keys (sort first!), accumulate gives running totals.

Worked example

1from itertools import groupby, accumulate, chain, permutations​
2​
3sales = [("east", 5), ("east", 3), ("west", 7)]​
4for region, rows in groupby(sales, key=lambda r: r[0]):​
5 print(region, sum(v for _, v in rows))​
6​
7print(list(accumulate([1, 2, 3, 4])))​
8print(list(chain([1, 2], [3])))​
9print(len(list(permutations(range(4)))))​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
groupby needs the input to be:

Lesson test

Take an 8-question test on “functools & itertools” — concepts, output prediction, bug spotting and interview questions.