How to Generate All Permutations of a List in Python

Hassan Saeed Feb 02, 2024
  1. Use itertools.permutations to Generate All Permutations of a List in Python
  2. Use Recursion to Generate All Permutations of a List in Python
How to Generate All Permutations of a List in Python

This tutorial discusses methods to generate all permutations of a list in Python.

Use itertools.permutations to Generate All Permutations of a List in Python

Python provides a standard library tool to generate permutations: itertools.permutation. The below example shows how to use this to generate all permutations of a list.

import itertools

inp_list = [4, 5, 6]
permutations = list(itertools.permutations(inp_list))
print(permutations)

Output:

[(4, 5, 6), (4, 6, 5), (5, 4, 6), (5, 6, 4), (6, 4, 5), (6, 5, 4)]

The default length of the permutation is set to be the length of the input list. However, we can specify the length of the permutation in the itertools.permutations function call. The below example illustrates this.

import itertools

inp_list = [1, 2, 3]
permutations = list(itertools.permutations(inp_list, r=2))
print(permutations)

Output:

[(4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5)]

The below example illustrates how to generate all permutations of all possible lengths of a given list.

import itertools

inp_list = [1, 2, 3]
permutations = []
for i in range(1, len(inp_list) + 1):
    permutations.extend(list(itertools.permutations(inp_list, r=i)))
print(permutations)

Output:

[(4,), (5,), (6,), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (4, 5, 6), (4, 6, 5), (5, 4, 6), (5, 6, 4), (6, 4, 5), (6, 5, 4)]

Use Recursion to Generate All Permutations of a List in Python

We can also use recursion to generate all permutations of a list in Python. The below example illustrates this.

def permutations(start, end=[]):
    if len(start) == 0:
        print(end)
    else:
        for i in range(len(start)):
            permutations(start[:i] + start[i + 1 :], end + start[i : i + 1])


permutations([4, 5, 6])

Output:

[4, 5, 6]
[4, 6, 5]
[5, 4, 6]
[5, 6, 4]
[6, 4, 5]
[6, 5, 4]

Related Article - Python List