Skip to content
dreamcode
dreamcode
Map
itertools
Lesson 54 of 77
+15 XP on finish
PYTHON ADVANCEDChapter 9 · Python Advanced

itertools and functools

The itertools module builds efficient loops for you: chain joins iterables end to end, combinations and permutations enumerate choices, groupby groups neighbouring items, and count counts forever. The functools module has tools for functions: reduce folds a list into one value, partial pre-fills some arguments, and lru_cache remembers results.

Worked example

How it reads

  • combinations(items, 2) gives every pair, ignoring order
  • reduce carries an accumulator through the whole list
  • partial(power, exp=2) is a new function with exp already filled in
Cloud tip: itertools functions return lazy iterators. Wrap them in list() when you want to see every value.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Print every possible pair from the crew as a list: [('Nova', 'Luka'), ('Nova', 'Mira'), ('Luka', 'Mira')].

Press Run to check your work.