Python Glossary Русский

all Python 3itertoolsfunction

itertools.permutations

itertools

All length-r permutations of the iterable (order matters).

Syntax

itertools.permutations(iterable, r=None)

The result count grows as n!/(n−r)!, so it explodes almost instantly on large inputs — don't wrap it in list() carelessly. Elements are treated as unique by position, not by value: two equal items like [1, 1] produce look-alike duplicate tuples, and if order within a group doesn't matter you want combinations instead.

Examples

import itertools
print(list(itertools.permutations([1, 2, 3], 2)))   # → [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print([''.join(p) for p in itertools.permutations('abc')])  # → ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
print(len(list(itertools.permutations(range(4)))))  # → 24
print(list(itertools.permutations('aab', 2)))  # → [('a', 'a'), ('a', 'b'), ('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'a')]
print(list(itertools.permutations([1, 2], 3)))  # → []

See also

Open in the full glossarydocs.python.orgReport an inaccuracy