Permutations are the various possible ways that elements in a collection can be arranged. For example if we have a set, {A, B, C}, the full-length permutations are as follows.

{A, B, C}
{A, C, B}
{B, A, C}
{B, C, A}
{C, B, A}
{C, A, B}
copy

The permutations() function in itertools module generates the permutations for a given iterable.

Syntax:
permutations(iterable, r = None)
copy
iterable Required. The iterable whose permutations we want.
r Optional. The length of the permutations to be returned. If not given it defaults to the length of the iterable.
Parameters:

The function returns an iterator of tuples where the tuple contains successive  r-length permutations of the elements of the given iterable. If r is not given only the full length permutations are returned.

ExampleEdit & Run
from itertools import permutations

data = ["A", "B", "C"]

perms = permutations(data)

for perm in perms:
    print(perm)
copy
Output:
('A', 'B', 'C') ('A', 'C', 'B') ('B', 'A', 'C') ('B', 'C', 'A') ('C', 'A', 'B') ('C', 'B', 'A') [Finished in 0.0105636827647686s]

 In the above example, we didn't specify the r parameter, hence the full-length permutations  were returned.

In the following example we us the permuations function with the r parameter given.

ExampleEdit & Run
from itertools import permutations

data = ["A", "B", "C"]

perms = permutations(data, r = 2)

for perm in perms:
    print(perm)
copy
Output:
('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B') [Finished in 0.009995215106755495s]

Generate all possible permutations

To generate all possible permutations of a given iterable, we can use a loop such that with each iteration, we specify a higher value for r until all the permutations are exhausted.

In the following example, we use a for loop to generate all possible permutations for the input iterable.

ExampleEdit & Run
from itertools import permutations

data = ["A", "B", "C"]

for i in range(len(data) + 1):
    print(f"\nlength {i}")

    #get the permutations with length i
    perms = permutations(data, r = i)
    print(*perms, sep = '\n')
copy
Output:
length 0 () length 1 ('A',) ('B',) ('C',) length 2 ('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B') length 3 ('A', 'B', 'C') ('A', 'C', 'B') ('B', 'A', 'C') ('B', 'C', 'A') ('C', 'A', 'B') ('C', 'B', 'A') [Finished in 0.009702363982796669s]