Skip to content

How do I generate all permutations of a list?

You can use the itertools.permutations() function to generate all permutations of a list in Python. Here is an example:

Generate all permutations of a list in Python using the itertools module

python
import itertools

my_list = [1, 2, 3]
result = list(itertools.permutations(my_list))
print(result)

This will output:


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

You can also specify the length of permutation using the second argument of permutations(iterable, r), for example:

Generate all permutations of a list in Python using the itertools module specifying the length of permutation

python
import itertools

my_list = [1, 2, 3]

result = list(itertools.permutations(my_list,2))
print(result)

this will output


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

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.