How to generating permutations with repetitions with Python?

Sometimes, we want to generating permutations with repetitions with Python.

In this article, we’ll look at how to generating permutations with repetitions with Python.

How to generating permutations with repetitions with Python?

To generating permutations with repetitions with Python, we can compute the cartesian product with itertools.product.

For instance, we write

import itertools

x = [1, 2, 3, 4, 5, 6]
prod = [p for p in itertools.product(x, repeat=2)]

to call itertools.product with list x and repeat set to 2 to get all permutations of any 2 items in list x with repetition.

Then we put the items in a list and assign it to prod.

Conclusion

To generating permutations with repetitions with Python, we can compute the cartesian product with itertools.product.