Tags

itertools Module

itertools Module

0 lessons
5 code snippets
2 community items

py-itertools

Code Snippets

5 snippets
Code Snippet

Flatten with itertools.chain

`itertools.chain` lazily concatenates several iterables into a single one without copying their elements, which is the right tool for flattening a list of lists by exactly one level. It works on any iterable (lists, tuples, generators, file objects), so it composes cleanly with the rest of the iterator toolbox. This entry covers `chain`, the unpacking-friendly `chain.from_iterable`, and how it differs from a recursive deep flatten.

Python
py-itertools
py-generators
iterators
py-standard-library

958

15

Easy
Code Snippet

Combinations and Permutations

When the problem reads 'pick K of N' or 'order all N', the right reflex in Python is `itertools.combinations` or `itertools.permutations`. Both are lazy iterators, so they enumerate huge search spaces without materializing them. This entry walks combinations, permutations, and `combinations_with_replacement`, plus when each is the right tool.

Python
py-itertools
py-generators
iterators
py-standard-library

235

2

Easy
Code Snippet

Group Consecutive Items with groupby

`itertools.groupby` collapses runs of equal-keyed items into `(key, group_iterator)` pairs. The catch is that it only groups *consecutive* equal items, so the input must already be sorted by the key if you want full grouping. This snippet covers run-length encoding, the sort-first idiom for dict-like grouping, and the iterator gotcha that bites every newcomer.

Python
py-itertools
py-generators
iterators
py-standard-library

768

5

Easy
Code Snippet

Pairwise Iteration

`itertools.pairwise` (Python 3.10+) yields successive overlapping pairs from any iterable. It replaces the classic `zip(seq, seq[1:])` and the `tee` recipe with a single, lazy, memory-flat call. This entry covers the basic pattern, the manual fallback for older Python, and a tiny example: detecting monotonic runs.

Python
py-itertools
py-generators
iterators
sliding-window

1k

27

Easy
Code Snippet

Build a Generator Pipeline

A generator pipeline chains small `yield`-based stages so data flows through them one item at a time. The result is constant-memory streaming over inputs that would not fit in RAM, with each stage doing one job (read, parse, filter, transform, sink). This entry shows a three-stage pipeline, how to compose stages dynamically, and why generator pipelines beat list-of-lists processing for log-style data.

Python
py-generators
iterators
py-itertools
py-standard-library

209

5

Medium