On this page
itertools
Prev: ipaddress | Up: stdlib_module | Next: json
Rel: functools, operator
Ref: docs.python.org — itertools
Tags: #public #python3 #stdlib
Import
import itertools
Overview
Memory-efficient, C-speed lazy iterator building blocks for slicing, chaining, grouping, batching, and combinatorics. Use itertools whenever you process large streams or pipelines without materializing intermediate lists in memory.
Quick Start
import itertools
flat = list(itertools.chain.from_iterable([[1, 2], [3, 4], [5]]))
assert flat == [1, 2, 3, 4, 5]
batches = list(itertools.batched(range(7), 3))
assert batches == [(0, 1, 2), (3, 4, 5), (6,)]
Implementation Walkthrough
1. Grouping Consecutive Records with groupby()
groupby() only groups adjacent items with the same key—always sort by the same key function first unless the input is already clustered:
import itertools
rows = [
{"dept": "eng", "name": "Ada"},
{"dept": "ops", "name": "Lin"},
{"dept": "eng", "name": "Grace"},
]
rows_sorted = sorted(rows, key=lambda r: r["dept"])
by_dept = {
dept: [r["name"] for r in group]
for dept, group in itertools.groupby(rows_sorted, key=lambda r: r["dept"])
}
assert by_dept == {"eng": ["Ada", "Grace"], "ops": ["Lin"]}
2. Windowing & Lazy Slicing (pairwise, islice)
import itertools
temps = [68, 70, 74, 71]
deltas = [b - a for a, b in itertools.pairwise(temps)]
assert deltas == [2, 4, -3]
first_three = list(itertools.islice(itertools.count(10, 5), 3))
assert first_three == [10, 15, 20]
Gotchas & Boundaries
groupby()requires pre-sorted input for global grouping, and each group iterator is invalidated as soon as the outer loop advances—materialize it (list(group)) if you keep it.- Iterators are single-use: Once consumed, an
itertoolsiterator is exhausted; never iterate over it twice without re-creating it. - Watch out with
tee(): If one branch falls far behind another,tee()buffers all intermediate items in memory. islice()does not support negative indices (islice(it, -3)raisesValueError) because iterators have unknown length.
Common Functions
- itertools.tee() —
tee(iterable, n=2, /)— Returns a tuple of n independent iterators.
Classes & Objects
- itertools.accumulate — Return series of accumulated sums (or other binary function results).
- itertools.batched — Batch data into tuples of length n. The last batch may be shorter than n.
- itertools.chain — Return a chain object whose .next() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted. (Methods:
.from_iterable()) - itertools.combinations — Return successive r-length combinations of elements in the iterable.
- itertools.combinations_with_replacement — Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats.
- itertools.compress — Return data elements corresponding to true selector elements.
- itertools.count — Return a count object whose .next() method returns consecutive values.
- itertools.cycle — Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.
- itertools.dropwhile — Drop items from the iterable while predicate(item) is true.
- itertools.filterfalse — Return those items of iterable for which function(item) is false.
- itertools.groupby — make an iterator that returns consecutive keys and groups from the iterable iterable Elements to divide into groups according to the key function.
- itertools.islice — islice(iterable, start, stop[, step]) --> islice object Return an iterator whose next() method returns selected values from an iterable. If start is specified, will skip all preceding elements;
- itertools.pairwise — Return an iterator of overlapping pairs taken from the input iterator.
- itertools.permutations — Return successive r-length permutations of elements in the iterable.
- itertools.product — Cartesian product of input iterables. Equivalent to nested for-loops.
- itertools.repeat — for the specified number of times. If not specified, returns the object endlessly.
- itertools.starmap — Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence.
- itertools.takewhile — Return successive entries from an iterable as long as the predicate evaluates to true for each entry.
- itertools.zip_longest — Return a zip_longest object whose .next() method returns a tuple where the i-th element comes from the i-th iterable argument. The .next() method continues until the longest iterable in the argument sequence
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/functools
- tuts/python3/stdlib_module/ipaddress
- tuts/python3/stdlib_module/itertools/accumulate
- tuts/python3/stdlib_module/itertools/batched
- tuts/python3/stdlib_module/itertools/chain
- tuts/python3/stdlib_module/itertools/combinations
- tuts/python3/stdlib_module/itertools/combinations_with_replacement
- tuts/python3/stdlib_module/itertools/compress
- tuts/python3/stdlib_module/itertools/count
- tuts/python3/stdlib_module/itertools/cycle
- tuts/python3/stdlib_module/itertools/dropwhile
- tuts/python3/stdlib_module/itertools/filterfalse
- tuts/python3/stdlib_module/itertools/groupby
- tuts/python3/stdlib_module/itertools/islice
- tuts/python3/stdlib_module/itertools/pairwise
- tuts/python3/stdlib_module/itertools/permutations
- tuts/python3/stdlib_module/itertools/product
- tuts/python3/stdlib_module/itertools/repeat
- tuts/python3/stdlib_module/itertools/starmap
- tuts/python3/stdlib_module/itertools/takewhile
- tuts/python3/stdlib_module/itertools/tee
- tuts/python3/stdlib_module/itertools/zip_longest
- tuts/python3/stdlib_module/json
- tuts/python3/stdlib_module/operator
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators
Related notes
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ipaddress Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/compress Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/count Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/cycle Linked here; links to this page; shared tags: #stdlib