Module itertools
Extra iterator methods and utilities.
- Crate
::itertools. - docs.rs
- crates.io
- GitHub
itertools extends Rust's iterator functionality with a rich collection
of additional iterator methods and utilities.
The crate provides the Itertools trait that adds dozens of useful methods
to any iterator, enabling powerful functional programming patterns.
It includes methods for grouping, batching, sorting, deduplication,
and complex iteration patterns that would otherwise require verbose loops.
Key features include chunk_by for grouping consecutive elements,
chunk for batching elements into fixed-size groups,
sorted for sorting without collecting first,
dedup for removing duplicates,
intersperse for inserting separators,
and cartesian_product for combining iterators.
The crate also provides standalone functions like zip_eq for
strict zipping that panics on length mismatches,
and repeat_n for creating repeating sequences.
Examples
Grouping consecutive elements:
use itertools::Itertools;
let data = vec![1, 1, 2, 2, 2, 3, 1, 1];
let groups: Vec<_> = data
.into_iter()
.chunk_by(|&x| x)
.into_iter()
.map(|(key, group)| (key, group.count()))
.collect();
assert_eq!(groups, [(1, 2), (2, 3), (3, 1), (1, 2)]);
Batching and processing in chunks:
use itertools::Itertools;
let data = 1..=10;
let chunks: Vec<Vec<_>> = data.chunks(3).into_iter().map(|chunk| chunk.collect()).collect();
assert_eq!(chunks, [vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], vec![10]]);
Combining iterators with cartesian product:
use itertools::Itertools;
let coords: Vec<_> = (0..3)
.cartesian_product(0..3)
.collect();
assert_eq!(coords.len(), 9);
assert_eq!(coords[0], (0, 0));
assert_eq!(coords[8], (2, 2));
Modules
Structs
-
AllEqualValueError
Value returned for the error case of
Itertools::all_equal_value. - ArrayWindows An iterator over all contiguous windows of the input iterator, producing arrays of a specific size.
- Batching A “meta iterator adaptor”. Its closure receives a reference to the iterator and may pick off as many elements as it likes, to produce the next iterator element.
- Chunk An iterator for the elements in a single chunk.
-
ChunkBy
ChunkByis the storage for the lazy grouping operation. - Chunks An iterator that yields the Chunk iterators.
- CircularArrayWindows An iterator over all windows, wrapping back to the first elements when the window would otherwise exceed the length of the iterator, producing arrays of a specific size.
- CircularTupleWindows An iterator over all windows, wrapping back to the first elements when the window would otherwise exceed the length of the iterator, producing tuples of a specific size.
-
ExactlyOneError
Iterator returned for the error case of
Itertoolsexactly_one()andat_most_one(). This iterator yields exactly the same elements as the input iterator. -
FilterMapOk
An iterator adapter to filter and apply a transformation on values within a nested
Result::Ok. -
FilterOk
An iterator adapter to filter values within a nested
Result::Ok. -
FlattenOk
An iterator adaptor that flattens
Result::Okvalues and allowsResult::Errvalues through unchanged. -
Format
Format all iterator elements lazily, separated by
sep. -
FormatWith
Format all iterator elements lazily, separated by
sep. - Group An iterator for the elements in a single group.
-
GroupingMap
GroupingMapis an intermediate struct for efficient group-and-fold operations. It groups elements by their key and at the same time fold each group using some aggregating operation. - Groups An iterator that yields the Group iterators.
- Interleave An iterator adaptor that alternates elements from two iterators until both run out.
- InterleaveShortest An iterator adaptor that alternates elements from the two iterators until one of them runs out.
- IntersperseWith An iterator adaptor to insert a particular value created by a function between each element of the adapted iterator.
-
IntoChunks
IntoChunksis the storage for a lazy chunking operation. - Iterate An iterator that infinitely applies function to value and yields results.
- KMergeBy An iterator adaptor that merges an arbitrary number of base iterators according to an ordering function.
- MergeBy An iterator adaptor that merges the two base iterators in ascending order. If both base iterators are sorted (ascending), the result is sorted.
-
MultiPeek
See [
multipeek()] for more information. -
MultiProduct
An iterator adaptor that iterates over the cartesian product of
multiple iterators of type
I. - PadUsing An iterator adaptor that pads a sequence to a minimum length by filling missing elements using a closure.
-
PeekNth
See [
peek_nth()] for more information. -
PeekingTakeWhile
An iterator adaptor that takes items while a closure returns
true. -
Permutations
An iterator adaptor that iterates through all the
k-permutations of the elements from an iterator. -
Position
The first component of the value yielded by
WithPosition. Indicates the position of this element in the iterator results. - Positions An iterator adapter to get the positions of each element that matches a predicate.
- Powerset An iterator to iterate through the powerset of the elements from an iterator.
-
ProcessResults
An iterator that produces only the
Tvalues as long as the inner iterator producesOk(T). -
Product
An iterator adaptor that iterates over the cartesian product of
the element sets of two iterators
IandJ. - PutBack An iterator adaptor that allows putting back a single item to the front of the iterator.
- PutBackN An iterator adaptor that allows putting multiple items in front of the iterator.
-
RcIter
A wrapper for
Rc<RefCell<I>>, that implements theIteratortrait. - RepeatN An iterator that produces n repetitions of an element.
-
StripPrefixError
The error returned by
Itertools::strip_prefixandItertools::strip_prefix_bywhen the iterator does not start with the requested prefix. -
TakeWhileInclusive
An iterator adaptor that consumes elements while the given predicate is
true, including the element for which the predicate first returnedfalse. -
TakeWhileRef
An iterator adaptor that borrows from a
Clone-able iterator to only pick off elements while the predicate returnstrue. - Tee One half of an iterator pair where both return the same elements.
- TupleBuffer An iterator over a incomplete tuple.
-
TupleCombinations
An iterator to iterate through all combinations in a
Clone-able iterator that produces tuples of a specific size. - TupleWindows An iterator over all contiguous windows that produces tuples of a specific size.
- Tuples An iterator that groups the items in tuples of a specific size.
-
Unfold
See
unfoldfor more information. - Unique An iterator adapter to filter out duplicate elements.
- UniqueBy An iterator adapter to filter out duplicate elements.
- Update An iterator adapter to apply a mutating function to each element before yielding it.
-
WhileSome
An iterator adaptor that filters
Option<A>iterator elements and producesA. Stops on the firstNoneencountered. -
WithPosition
An iterator adaptor that wraps each element in an
Position. -
Zip
See
multizipfor more information. - ZipEq An iterator which iterates two other iterators simultaneously and panic if they have different lengths.
-
ZipLongest
An iterator which iterates two other iterators simultaneously
and wraps the elements in
EitherOrBoth.
Enums
-
Diff
A type returned by the
diff_withfunction. -
Either
The enum
Eitherwith variantsLeftandRightis a general purpose sum type with two cases. - EitherOrBoth Value that either holds a single A or B, or both.
-
FoldWhile
An enum used for controlling the execution of
fold_while. -
MinMaxResult
MinMaxResultis an enum returned byminmax.
Traits
-
Itertools
An
Iteratorblanket implementation that provides extra adaptors and methods. - MultiUnzip An iterator that can be unzipped into multiple collections.
- PeekingNext An iterator that allows peeking at an element before deciding to accept it.
Functions
-
assert_equal
Assert that two iterables produce equal sequences, with the same
semantics as
equal(a, b). -
concat
Combine all an iterator's elements into one element by using
Extend. -
cons_tuples
Create an iterator that maps for example iterators of
((A, B), C)to(A, B, C). -
diff_with
Compares every element yielded by both
iandjwith the given function in lock-step and returns aDiffwhich describes howjdiffers fromi. -
equal
Return
trueif both iterables produce equal sequences (elements pairwise equal and sequences of the same length),falseotherwise. - iterate Creates a new iterator that infinitely applies function to value and yields results.
- kmerge_by Create an iterator that merges elements of the contained iterators.
- multiunzip Converts an iterator of tuples into a tuple of containers.
-
multizip
An iterator that generalizes
.zip()and allows running multiple iterators in lockstep. -
partition
Partition a sequence using predicate
predso that elements that map totrueare placed before elements which map tofalse. -
process_results
“Lift” a function of the values of an iterator so that it can process
an iterator of
Resultvalues instead. -
repeat_n
Create an iterator that produces
nrepetitions ofelement. - unfold Creates a new unfold source with the specified closure as the "iterator function" and an initial state to eventually pass to the closure
Type Aliases
-
ArrayCombinations
Iterator for const generic combinations returned by
.array_combinations() - Coalesce An iterator adaptor that may join together adjacent elements.
-
Combinations
Iterator for
Vecvalued combinations returned by.combinations() -
CombinationsWithReplacement
Iterator for
Box<[I]>valued combinations_with_replacement returned by.combinations_with_replacement() -
ConsTuples
An iterator that maps an iterator of tuples like
((A, B), C)to an iterator of(A, B, C). - Dedup An iterator adaptor that removes repeated duplicates.
- DedupBy An iterator adaptor that removes repeated duplicates, determining equality using a comparison function.
- DedupByWithCount An iterator adaptor that removes repeated duplicates, while keeping a count of how many repeated elements were present. This will determine equality using a comparison function.
- DedupWithCount An iterator adaptor that removes repeated duplicates, while keeping a count of how many repeated elements were present.
- Duplicates An iterator adapter to filter out duplicate elements.
- DuplicatesBy An iterator adapter to filter for duplicate elements.
-
GroupBy
See
ChunkBy. -
GroupingMapBy
GroupingMapByis an intermediate struct for efficient group-and-fold operations. - Intersperse An iterator adaptor to insert a particular value between each element of the adapted iterator.
- KMerge An iterator adaptor that merges an arbitrary number of base iterators in ascending order. If all base iterators are sorted (ascending), the result is sorted.
-
MapInto
An iterator adapter to apply
Intoconversion to each element. -
MapOk
An iterator adapter to apply a transformation within a nested
Result::Ok. - Merge An iterator adaptor that merges the two base iterators in ascending order. If both base iterators are sorted (ascending), the result is sorted.
- MergeJoinBy An iterator adaptor that merge-joins items from the two base iterators in ascending order.