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.
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. |
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.
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.
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.