Skip to main content

Iterators and Generators

itertools Essentials

0:00
LearnStep 1/3

Efficient Iteration with itertools

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.

python

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.

python

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.
python

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.

python

batched() (Python 3.12+) splits an iterable into tuples of a specific length.

python

Combinatorics

permutations(iterable, r) returns all possible orderings of length r without repeated elements.

python