This post will discuss how to generate all possible permutations of a list in Python.

1. Generate full-length permutations

In Python, you can use the in-built module itertools to get the permutations of elements in the list using the permutations() function. It defaults to the length of the list and hence generates all possible permutations.

Download  Run Code

 
The above code will result in the following list. Since the permutations() function returns generators, we have converted it to a list.

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

2. Generate successive r length permutations

To generate permutations of specific length r, pass r as the second argument to the permutations() function.

Download  Run Code

 
This will result in the following permutations of length 2:

[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

3. Generate combinations of a given length

Additionally, if you need subsequences of elements from the input list of the desired length, you can use the itertools.combinations.

Download  Run Code

 
This will result in the following combinations of length 2. Note that the order does not matter in combinations.

[(1, 2), (1, 3), (2, 3)]

4. Generate Cartesian product

Finally, if you need a Cartesian product of several iterables, consider using the itertools.product.

Download  Run Code

Output:

[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

 
You can also compute the product of an iterable with itself. You can do this by specifying the total number of repetitions with the repeat argument shown below:

Download  Run Code

Output:

[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

That’s all about generating all permutations of a list in Python.