How to Calculate Permutations in Python

To calculate permutations in Python, you can use the itertools.permutations() function. 

This function returns all possible permutations of a given iterable, such as a list, dictionary, tuple, or string.

Example 1: Generating Permutations of a List

Visual Representation

Calculate Permutations of list in Python

import itertools 
 
new_list = [21, 18, 19]

perm = itertools.permutations(new_list) 
 
for i in list(perm): 
  print(i)

Output

(21, 18, 19)
(21, 19, 18)
(18, 21, 19)
(18, 19, 21)
(19, 21, 18)
(19, 18, 21)

Example 2: Generating Permutations of a Tuple

Visual Representation

Passing Tuple

import itertools 

sample_tuple = (21, 19)

perm = itertools.permutations(sample_tuple)

for item in perm:
 print(item)

Output

(21, 19)
(19, 21)

Example 3: Generating Permutations of a Dictionary

The permutations() function does not produce permutations of the dictionary itself, but rather of the dictionary’s keys (by default).

However, you can also produce permutations of the dictionary’s values using the dictionary.values() method.

import itertools

sample_dict = { 1: 19, 2: 21, 3: 18}

# Calculating permutations of the dictionary's keys
permutations = itertools.permutations(sample_dict, 3)  # Choosing 3 keys for each permutation

# Printing the permutations
for perm in permutations:
 print(perm)

Output

(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

1 thought on “How to Calculate Permutations in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.