Generate all permutations of a Python list
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.
|
1 2 3 4 5 6 7 8 9 |
import itertools if __name__ == '__main__': nums = [1, 2, 3] permutations = list(itertools.permutations(nums)) print(permutations) |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import itertools if __name__ == '__main__': nums = [1, 2, 3] r = 2 permutations = list(itertools.permutations(nums, r)) print(permutations) |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import itertools if __name__ == '__main__': nums = [1, 2, 3] r = 2 combinations = list(itertools.combinations(nums, r)) print(combinations) |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import itertools if __name__ == '__main__': x = [1, 2, 3] y = [4, 5] products = list(itertools.product(x, y)) print(products) |
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:
|
1 2 3 4 5 6 7 8 9 |
import itertools if __name__ == '__main__': x = [1, 2, 3] products = list(itertools.product(x, repeat=2)) print(products) |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)