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:

import itertools

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

This will output:

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

Watch a course Python - The Practical Guide

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

import itertools

my_list = [1, 2, 3]

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

this will output

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