Sometimes, we want to generate all permutations of a list with Python.
In this article, we’ll look at how to generate all permutations of a list with Python.
How to generate all permutations of a list with Python?
To generate all permutations of a list with Python, we can use the itertools.permutations
method.
For instance, we write:
import itertools
perms = list(itertools.permutations([1, 2, 3]))
print(perms)
We call itertools.permtations
with a list to get all the permutations from.
It returns a iterator with all the permutations of [1, 2, 3]
.
Next, we convert the iterator to a list with list
and assign it to perms
.
Therefore, perms
is:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
Conclusion
To generate all permutations of a list with Python, we can use the itertools.permutations
method.