cid 13353b99a072a7a58f8e97d09e27494c0e81dac732361d11e29976740fdc5171 · original · open access · via pydoc
Title: itertools — Functions creating iterators for efficient looping — Python 3.13.18 documentation
Authors:
Venue: pydoc
Year: 2001
Canonical: pydoc:itertools@3.13
URL: https://docs.python.org/3.13/library/itertools.html
Collector: pydoc
OA: true
ABSTRACT
itertools — Functions creating iterators for efficient looping — Python 3.13.18 documentation Navigation index modules | next | previous | Python » 3.13.18 Documentation » The Python standard library » Functional Programming Modules » itertools — Functions creating iterators for efficient looping | Theme Auto Light Dark | itertools — Functions creating iterators for efficient looping¶ This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python. For instance, SML provides a tabulation tool: tabulate(f) which produces a sequence f(0), f(1), .... The same effect can be achieved in Python by combining map() and count() to form map(f, count()). Infinite iterators: Iterator Arguments Results Example count() [start[, step]] start, start+step, start+2*step, … count(10) → 10 11 12 13 14 ... cycle() p p0, p1, … plast, p0, p1, … cycle('ABCD') → A B C D A B C D ... repeat() elem [,n] elem, elem, elem, … endlessly or up to n times repeat(10, 3) → 10 10 10 Iterators terminating on the shortest input sequence: Iterator Arguments Results Example accumulate() p [,func] p0, p0+p1, p0+p1+p2, … accumulate([1,2,3,4,5]) → 1 3 6 10 15 batched() p, n (p0, p1, …, p_n-1), … batched('ABCDEFG', n=3) → ABC DEF G chain() p, q, … p0, p1, … plast, q0, q1, … chain('ABC', 'DEF') → A B C D E F chain.from_iterable() iterable p0, p1, … plast, q0, q1, … chain.from_iterable(['ABC', 'DEF']) → A B C D E F compress() data, selectors (d[0] if s[0]), (d[1] if s[1]), … compress('ABCDEF', [1,0,1,0,1,1]) → A C E F dropwhile() predicate, seq seq[n], seq[n+1], starting when predicate fails dropwhile(lambda x: x data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] list(accumulate(data, max)) # running maximum [3, 4, 6, 6, 6, 9, 9, 9, 9, 9] list(accumulate(data, operator.mul)) # running product [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0] # Amortize a 5% loan of 1000 with 10 annual payments of 90 update = lambda balance, payment: round(balance * 1.05) - payment list(accumulate(repeat(90, 10), update, initial=1_000)) [1000, 960, 918, 874, 828, 779, 728, 674, 618, 559, 497] See functools.reduce() for a similar function that returns only the final accumulated value. Added in version 3.2. Changed in version 3.3: Added the optional function parameter. Changed in version 3.8: Added the optional initial parameter. itertools.batched(iterable, n, *, strict=False)¶ Batch data from the iterable into tuples of length n. The last batch may be shorter than n. If strict is true, will raise a ValueError if the final batch is shorter than n. Loops over the input iterable and accumulates data into tuples up to size n. The input is consumed lazily, just enough to fill a batch. The result is yielded as soon as the batch is full or when the input iterable is exhausted: flattened_data = ['roses', 'red', 'violets', 'blue', 'sugar', 'sweet'] unflattened = list(batched(flattened_data, 2)) unflattened [('roses', 'red'), ('violets', 'blue'), ('sugar', 'sweet')] Roughly equivalent to: def batched(iterable, n, *, strict=False): # batched('ABCDEFG', 3) → ABC DEF G if n n. The combination tuples are emitted in lexicographic order according to the order of the input iterable. If the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. If the input elements are unique, there will be no repeated values within each combination. Roughly equivalent to: def combinations(iterable, r): # combinations('ABCD', 2) → AB AC AD BC BD CD # combinations(range(4), 3) → 012 013 023 123 pool = tuple(iterable) n = len(pool) if r n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) itertools.combinations_with_replacement(iterable, r)¶ Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. The output is a subsequence of product() that keeps only entries that are subsequences (with possible repeated elements) of the iterable. The number of subsequence returned is (n + r - 1)! / r! / (n - 1)! when n 0. The combination tuples are emitted in lexicographic order according to the order of the input iterable. if the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. If the input elements are unique, the generated combinations will also be unique. Roughly equivalent to: def combinations_with_replacement(iterable, r): # combinations_with_replacement('ABC', 2) → AA AB AC BB BC CC pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices) Added in version 3.1. itertools.compress(data, selectors)¶ Make an iterator that returns elements from data where the corresponding element in selectors is true. Stops when either the data or selectors iterables have been exhausted. Roughly equivalent to: def compress(data, selectors): # compress('ABCDEF', [1,0,1,0,1,1]) → A C E F return (datum for datum, selector in zip(data, selectors) if selector) Added in version 3.1. itertools.count(start=0, step=1)¶ Make an iterator that returns evenly spaced values beginning with start. Can be used with map() to generate consecutive data points or with zip() to add sequence numbers. Roughly equivalent to: def count(start=0, step=1): # count(10) → 10 11 12 13 14 ... # count(2.5, 0.5) → 2.5 3.0 3.5 ... n = start while True: yield n n += step When counting with floating-point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: (start + step * i for i in count()). Changed in version 3.1: Added step argument and allowed non-integer arguments. itertools.cycle(iterable)¶ Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to: def cycle(iterable): # cycle('ABCD') → A B C D A B C D A B C D ... saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element This itertool may require significant auxiliary storage (depending on the length of the iterable). itertools.dropwhile(predicate, iterable)¶ Make an iterator that drops elements from the iterable while the predicate is true and afterwards returns every element. Roughly equivalent to: def dropwhile(predicate, iterable): # dropwhile(lambda x: x n. The permutation tuples are emitted in lexicographic order according to the order of the input iterable. If the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. If the input elements are unique, there will be no repeated values within a permutation. Roughly equivalent to: def permutations(iterable, r=None): # permutations('ABCD', 2) → AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) → 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r n: return indices = list(range(n)) cycles = list(range(n, n-r, -1)) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return itertools.product(*iterables, repeat=1)¶ Cartesian product of the input iterables. Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B). The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order. To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A). This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory: def product(*iterables, repeat=1): # product('ABCD', 'xy') → Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) → 000 001 010 011 100 101 110 111 if repeat list(map(pow, range(10), repeat(2))) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] itertools.starmap(function, iterable)¶ Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters have already been “pre-zipped” into tuples. The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). Roughly equivalent to: def starmap(function, iterable): # starmap(pow, [(2,5), (3,2), (10,3)]) → 32 9 1000 for args in iterable: yield function(*args) itertools.takewhile(predicate, iterable)¶ Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to: def takewhile(predicate, iterable): # takewhile(lambda x: x iterator = iter('abcdef') [iterator] = tee(iterator, 1) # Make the input peekable next(iterator) # Move the iterator forward 'a' lookahead(iterator) # Check next value 'b' next(iterator) # Continue moving forward 'b' tee iterators are not threadsafe. A RuntimeError may be raised when simultaneously using iterators returned by the same tee() call, even if the original iterable is threadsafe. This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee(). itertools.zip_longest(*iterables, fillvalue=None)¶ Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. If not specified, fillvalue defaults to None. Iteration continues until the longest iterable is exhausted. Roughly equivalent to: def zip_longest(*iterables, fillvalue=None): # zip_longest('ABCD', 'xy', fillvalue='-') → Ax By C- D- iterators = list(map(iter, iterables)) num_active = len(iterators) if not num_active: return while True: values = [] for i, iterator in enumerate(iterators): try: value = next(iterator) except StopIteration: num_active -= 1 if not num_active: return iterators[i] = repeat(fillvalue) value = fillvalue values.append(value) yield tuple(values) If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). Itertools Recipes¶ This section shows recipes for creating an extended toolset using the existing itertools as building blocks. The primary purpose of the itertools recipes is educational. The recipes show various ways of thinking about individual tools — for example, that chain.from_iterable is related to the concept of flattening. The recipes also give ideas about ways that the tools can be combined — for example, how starmap() and repeat() can work together. The recipes also show patterns for using itertools with the operator and collections modules as well as with the built-in itertools such as map(), filter(), reversed(), and enumerate(). A secondary purpose of the recipes is to serve as an incubator. The accumulate(), compress(), and pairwise() itertools started out as recipes. Currently, the sliding_window(), iter_index(), and sieve() recipes are being tested to see whether they prove their worth. Substantially all of these recipes and many, many others can be installed from the more-itertools project found on the Python Package Index: python -m pip install more-itertools Many of the recipes offer the same high performance as the underlying toolset. Superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once. Code volume is kept small by linking the tools together in a functional style. High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead. from collections import Counter, deque from contextlib import suppress from functools import reduce from math import comb, prod, sumprod, isqrt from operator import itemgetter, getitem, mul, neg, truediv def take(n, iterable): "Return first n items of the iterable as a list." return list(islice(iterable, n)) def prepend(value, iterable): "Prepend a single value in front of an iterable." # prepend(1, [2, 3, 4]) → 1 2 3 4 return chain([value], iterable) def running_mean(iterable): "Yield the average of all values seen so far." # running_mean([8.5, 9.5, 7.5, 6.5]) → 8.5 9.0 8.5 8.0 return map(truediv, accumulate(iterable), count(1)) def repeatfunc(function, times=None, *args): "Repeat calls to a function with specified arguments." if times is None: return starmap(function, repeat(args)) return starmap(function, repeat(args, times)) def flatten(list_of_lists): "Flatten one level of nesting." return chain.from_iterable(list_of_lists) def ncycles(iterable, n): "Returns the sequence elements n times." return chain.from_iterable(repeat(tuple(iterable), n)) def loops(n): "Loop n times. Like range(n) but without creating integers." # for _ in loops(100): ... return repeat(None, n) def tail(n, iterable): "Return an iterator over the last n items." # tail(3, 'ABCDEFG') → E F G return iter(deque(iterable, maxlen=n)) def consume(iterator, n=None): "Advance the iterator n-steps ahead. If n is None, consume entirely." # Use functions that consume iterators at C speed. if n is None: deque(iterator, maxlen=0) else: next(islice(iterator, n, n), None) def nth(iterable, n, default=None): "Returns the nth item or a default value." return next(islice(iterable, n, None), default) def quantify(iterable, predicate=bool): "Given a predicate that returns True or False, count the True results." return sum(map(predicate, iterable)) def first_true(iterable, default=False, predicate=None): "Returns the first true value or the *default* if there is no true value." # first_true([a,b,c], x) → a or b or c or x # first_true([a,b], x, f) → a if f(a) else b if f(b) else x return next(filter(predicate, iterable), default) def all_equal(iterable, key=None): "Returns True if all the elements are equal to each other." # all_equal('4٤௪౪໔', key=int) → True return len(take(2, groupby(iterable, key))) 2: yield 2 data = bytearray((0, 1)) * (n // 2) for p in iter_index(data, 1, start=3, stop=isqrt(n) + 1): data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p))) yield from iter_index(data, 1, start=3) def factor(n): "Prime factors of n." # factor(99) → 3 3 11 # factor(1_000_000_000_000_007) → 47 59 360620266859 # factor(1_000_000_000_000_403) → 1000000000000403 for prime in sieve(isqrt(n) + 1): while not n % prime: yield prime n //= prime if n == 1: return if n 1: yield n def is_prime(n): "Return True if n is prime." # is_prime(1_000_000_000_000_403) → True return n 1 and next(factor(n)) == n def totient(n): "Count of natural numbers up to n that are coprime to n." # https://mathworld.wolfram.com/TotientFunction.html # totient(12) → 4 because len([1, 5, 7, 11]) == 4 for prime in set(factor(n)): n -= n // prime return n Table of Contents itertools — Functions creating iterators for efficient looping Itertool Functions Itertools Recipes Previous topic Functional Programming Modules Next topic functools — Higher-order functions and operations on callable objects This page Report a bug Show source « Navigation index modules | next | previous | Python » 3.13.18 Documentation » The Python standard library » Functional Programming Modules » itertools — Functions creating iterators for efficient looping | Theme Auto Light Dark | © Copyright 2001-2026, Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Oct 26, 2026 (13:10 UTC). Found a bug? Created using Sphinx 8.2.3.