Skip to main content

Lib/itertools.py

Source:

cpython 3.14 @ ab2d84fe1023/Modules/itertoolsmodule.c

itertools is implemented entirely in C (Modules/itertoolsmodule.c). There is no Lib/itertools.py. The module provides lazy iterators for efficient looping without creating intermediate lists.

Map

SymbolCategoryRole
count(start, step)InfiniteArithmetic counter
cycle(iterable)InfiniteRepeat iterable infinitely
repeat(obj, times)InfiniteRepeat an object N times
chain(*iterables)CombiningConcatenate iterables
chain.from_iterable(it)CombiningFlatten one level
islice(it, stop)SlicingIterator slice
compress(data, selectors)FilteringFilter by boolean mask
filterfalse(pred, it)FilteringElements where pred is False
dropwhile(pred, it)FilteringDrop while pred is True
takewhile(pred, it)FilteringTake while pred is True
starmap(func, it)Mappingfunc(*args) for each args in it
zip_longest(*its, fillvalue)CombiningZip with fill for uneven lengths
groupby(it, key)GroupingGroup consecutive equal-key elements
accumulate(it, func, initial)AccumulatingRunning reduction
product(*its, repeat)CombinatoricCartesian product
permutations(it, r)Combinatoricr-length permutations
combinations(it, r)Combinatoricr-length combinations without replacement
combinations_with_replacement(it, r)CombinatoricWith replacement
pairwise(it)Sliding windowOverlapping pairs (3.10+)
batched(it, n)BatchingNon-overlapping n-tuples (3.12+)

Reading

groupby semantics

groupby(iterable, key) groups consecutive elements that share the same key value. It does NOT sort the input; callers that want all elements with the same key together must sort first.

# CPython: Modules/itertoolsmodule.c groupby_next
for key, group in itertools.groupby(['aab', 'abb', 'bbc'], key=lambda s: s[0]):
print(key, list(group))
# a ['aab']
# a ['abb'] <-- not grouped with previous 'a' because 'b' appeared in between
# b ['bbc']

accumulate with initial

# CPython: Modules/itertoolsmodule.c accumulate_next
list(itertools.accumulate([1, 2, 3, 4], operator.mul, initial=1))
# [1, 1, 2, 6, 24]

initial (Python 3.8+) prepends a starting value. Equivalent to reduce but returns all intermediate results.

batched (Python 3.12+)

# CPython: Modules/itertoolsmodule.c batched_next
list(itertools.batched('ABCDE', 3))
# [('A', 'B', 'C'), ('D', 'E')]

Returns tuples of exactly n items; the last tuple may be shorter.

pairwise (Python 3.10+)

# CPython: Modules/itertoolsmodule.c pairwise_next
list(itertools.pairwise('ABCD'))
# [('A', 'B'), ('B', 'C'), ('C', 'D')]

gopy notes

Status: not yet ported. Pure-Go lazy iterators are straightforward to implement with closures or structs. product, permutations, and combinations are the most complex (they maintain state arrays). groupby requires careful handling of the sub-iterator lifetime.