More Itertools

Python’s itertools library is a gem - you can compose elegant solutions for a variety of problems with the functions it provides. In more-itertools we collect additional building blocks, recipes, and routines for working with Python iterables.

Grouping chunked, sliced, distribute, divide, split_at, split_before, split_after, bucket, grouper, partition
Lookahead and lookback spy, peekable, seekable
Windowing windowed, stagger, pairwise
Augmenting count_cycle, intersperse, padded, adjacent, groupby_transform, padnone, ncycles
Combining collapse, sort_together, interleave, interleave_longest, collate, zip_offset, dotproduct, flatten, roundrobin, prepend
Summarizing ilen, first, last, one, unique_to_each, locate, rlocate, consecutive_groups, exactly_n, run_length, map_reduce, all_equal, first_true, nth, quantify
Selecting islice_extended, strip, lstrip, rstrip, take, tail, unique_everseen, unique_justseen
Combinatorics distinct_permutations, circular_shifts, powerset, random_product, random_permutation, random_combination, random_combination_with_replacement, nth_combination
Wrapping always_iterable, consumer, with_iter, iter_except
Others replace, numeric_range, always_reversible, side_effect, iterate, difference, make_decorator, SequenceView, consume, accumulate, tabulate, repeatfunc

Getting started

To get started, install the library with pip:

pip install more-itertools

The recipes from the itertools docs are included in the top-level package:

>>> from more_itertools import flatten
>>> iterable = [(0, 1), (2, 3)]
>>> list(flatten(iterable))
[0, 1, 2, 3]

Several new recipes are available as well:

>>> from more_itertools import chunked
>>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list(chunked(iterable, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

>>> from more_itertools import spy
>>> iterable = (x * x for x in range(1, 6))
>>> head, iterable = spy(iterable, n=3)
>>> list(head)
[1, 4, 9]
>>> list(iterable)
[1, 4, 9, 16, 25]

For the full listing of functions, see the API documentation.


more-itertools is maintained by @erikrose and @bbayles, with help from many others. If you have a problem or suggestion, please file a bug or pull request in this repository. Thanks for contributing!