Python itertools.permutations() Function
The Python itertools.permutations() function is used to generate all possible ordered arrangements (permutations) of elements from a given iterable. It allows you to specify the length of each permutation.
This function is useful in combinatorial problems where order matters, such as password generation, game mechanics, and arrangement problems.
Syntax
Following is the syntax of the Python itertools.permutations() function −
itertools.permutations(iterable, r=None)
Parameters
This function accepts the following parameters −
- iterable: The input iterable whose elements will be arranged in different orders.
- r (optional): The length of each permutation. If not specified, it defaults to the length of the iterable.
Return Value
This function returns an iterator that produces tuples representing all possible permutations.
Example 1
Following is an example of the Python itertools.permutations() function. Here, we generate all possible orderings of a list of numbers −
import itertools numbers = [1, 2, 3] result = itertools.permutations(numbers) for item in result: print(item)
Following is the output of the above code −
(1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1)
Example 2
Here, we specify a permutation length of 2, generating pairs of elements from the given set −
import itertools letters = ['A', 'B', 'C'] result = itertools.permutations(letters, 2) for item in result: print(item)
Output of the above code is as follows −
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')
Example 3
Now, we use itertools.permutations() function to generate all possible orders of characters in a string −
import itertools
word = "DOG"
result = itertools.permutations(word)
for item in result:
print(''.join(item))
The result obtained is as shown below −
DOG DGO ODG OGD GDO GOD
Example 4
When working with passwords or combination locks, the itertools.permutations() function can help generate all possible sequences −
import itertools
digits = ['1', '2', '3']
result = itertools.permutations(digits, 3)
for combination in result:
print(''.join(combination))
The result produced is as follows −
123 132 213 231 312 321
python_modules.htm