Skip to the solution
MediumDSA6 min read

What is the itertools module used for?

68 views

The problem

Question presented to candidate: "What is itertools for? Name a few functions you actually use, and tell me about one that has a surprising behaviour."

What a strong answer should cover:

  • itertools is a standard-library module of fast, memory-efficient building blocks that take iterables and return lazy iterators; they are implemented in C and compose into pipelines.
  • The three families: infinite iterators (count, cycle, repeat), iterators that stop on the shortest input (chain, islice, accumulate, compress, takewhile, dropwhile, groupby, starmap, zip_longest, pairwise, tee), and combinatoric iterators (product, permutations, combinations, combinations_with_replacement).
  • The classic gotchas: groupby only groups consecutive equal keys (sort first) and its groups are invalidated when you advance; tee buffers and the original iterator must not be used afterwards; infinite iterators need a bound.
  • Version facts that come up: pairwise is new in 3.10, batched in 3.12 (with strict= in 3.13); before that people used the documented recipes.
  • When to use it: replacing nested loops (product), slicing streams (islice), flattening (chain.from_iterable), running totals (accumulate), windows and batches.

Code / implementation expected: Optional โ€” a couple of one-liners (e.g. groupby after sorted, islice on a generator, chain.from_iterable to flatten).

  • itertools

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read ยท 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA tour of itertools: infinite and terminating iterators
Pythongroupby gotchas, tee, and the combinatoric iterators
PythonThe itertools recipes written for Python 3.11

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 115 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What does __slots__ do?

Continue