Iterators & Generators
itertools Module
The itertools standard library — efficient iteration tools including infinite iterators, combinatoric functions, grouping, and chaining utilities.
Interview: Shows advanced Python knowledge — interviewers value candidates who use itertools instead of hand-rolled loops.
The itertools module provides fast, memory-efficient tools for creating and manipulating iterators. These functions are implemented in C and are significantly faster than equivalent Python loops. They fall into three categories: infinite iterators, finite iterators, and combinatoric generators.
Infinite Iterators
count(start, step)— counts from start indefinitely: 10, 11, 12, ...cycle(iterable)— repeats the iterable endlessly: A, B, C, A, B, C, ...repeat(obj, times)— repeats an object (optionally limited times)
Finite Iterators
chain(*iterables)— concatenates multiple iterables into one sequenceislice(iterable, stop)— takes a slice of an iterator (like list slicing but lazy)zip_longest(*iterables)— like zip() but fills shorter iterables with a fillvaluegroupby(iterable, key)— groups consecutive elements by a key functionaccumulate(iterable)— running totals: 1, 3, 6, 10, ... (cumulative sum)takewhile/dropwhile— take/drop items while a predicate is true
Combinatoric Functions
product(*iterables)— Cartesian product (all combinations)permutations(iterable, r)— all ordered arrangements of length rcombinations(iterable, r)— all unordered selections of length rcombinations_with_replacement— combinations allowing repeated elements
Interview Insight
Using itertools in interviews shows Python maturity. Know chain for flattening, groupby for grouping, product for Cartesian products, and islice for taking finite items from infinite iterators.
Use Cases
Data flattening — chain.from_iterable to flatten nested lists
Generating test data — product/permutations for all combinations
Grouping data — groupby for clustering sorted records
Running calculations — accumulate for cumulative sums/products
Memory-efficient iteration — islice for finite portions of infinite streams
Common Mistakes
Forgetting groupby requires sorted input — only groups CONSECUTIVE equal elements
Using list(product(...)) on large iterables — creates enormous list in memory
Not wrapping itertools results in list() for debugging — they are iterators, consumed once
Confusing permutations (ordered) with combinations (unordered)
Forgetting islice for infinite iterators — without it, you get an infinite loop