How to Calculate Permutations in Python

09/15/2021

Contents

In this article, you will learn how to calculate permutations in Python.

Calculate Permutations

To calculate permutations in Python, you can use the built-in permutations function from the itertools module. Here’s an example:

import itertools

# Calculate permutations of a list
my_list = [1, 2, 3]
permutations = list(itertools.permutations(my_list))
print(permutations)

# Calculate permutations of a string
my_string = "abc"
permutations = list(itertools.permutations(my_string))
print(permutations)

In this example, we import the itertools module and use the permutations function to calculate permutations of a list and a string. The permutations function returns an iterator, so we convert it to a list using the list function. The output will be a list of tuples, where each tuple represents a permutation.

If you want to calculate permutations of a specific length, you can pass the length as a second argument to the permutations function. For example:

import itertools

# Calculate permutations of a list of length 2
my_list = [1, 2, 3]
permutations = list(itertools.permutations(my_list, 2))
print(permutations)

In this example, we calculate permutations of length 2 of a list. The output will be a list of tuples, where each tuple has length 2.