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:
itertoolsis 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:
groupbyonly groups consecutive equal keys (sort first) and its groups are invalidated when you advance;teebuffers and the original iterator must not be used afterwards; infinite iterators need a bound. - Version facts that come up:
pairwiseis new in 3.10,batchedin 3.12 (withstrict=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).