itertools provides memory-efficient iterators; functools offers higher-order function utilities like lru_cache and partial—stdlib functional tools without third-party deps.
itertools examples
from itertools import islice, chain, groupby
first_three = list(islice(range(10), 3))
combined = list(chain([1, 2], [3, 4]))
functools examples
from functools import lru_cache, partial
@lru_cache(maxsize=128)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
double = partial(pow, exp=2)
Important interview questions and answers
- Q: lru_cache use case?
A: Memoize pure function results—speeds recursive or expensive calls; watch memory with large inputs. - Q: itertools vs list comprehensions?
A: itertools streams lazily—better for large or infinite sequences.
Self-check
- What decorator caches function results?
- What does partial(pow, exp=2) create?
Tip: @lru_cache memoizes pure functions—do not cache functions with side effects.
Interview prep
- lru_cache when?
Pure expensive functions with repeated args—watch memory with unbounded cache.
- itertools lazy benefit?
Process large/infinite iterables without building full lists in memory.