Python's itertools module provides a collection of fast, memory-efficient tools for creating iterators. These functions work lazily, meaning they generate items one by one rather than building large lists in memory.
Chaining and Zipping
chain() combines multiple iterables into a single continuous stream.
zip_longest() is similar to the built-in zip(), but instead of stopping at the shortest iterable, it continues until the longest one is exhausted, filling missing values with a specified fillvalue.
Filtering with Predicates
Unlike filter() which checks every element, these functions depend on the sequence order.
takewhile(predicate, iterable): Returns elements as long as the predicate is true, then stops.dropwhile(predicate, iterable): Skips elements as long as the predicate is true, then yields the rest of the iterable.
Grouping and Batching
groupby() groups consecutive elements that share a common key. Note: The input should generally be sorted by the key first, as it only groups consecutive matches.
batched() (Python 3.12+) splits an iterable into tuples of a specific length.
Combinatorics
permutations(iterable, r) returns all possible orderings of length r without repeated elements.