generate list permutations in python

How to Generate All Permutation of List in Python

Python lists are powerful data structures to store diverse data. Sometimes you may need to generate all permutations of list in Python. In this article, we will learn how to generate all permutations of list in Python.

How to Generate All Permutation of List in Python

Let us say you have the following list.

lst = [1, 2, 3]

There are several ways to get all permutations of list in Python. One of the simplest method is to use itertools.permutations.

import itertools
list(itertools.permutations(lst))
OR
import itertools
list(itertools.permutations([1, 2, 3]))

The above function is capable of handling even large lists. Alternatively, if you want to implement it yourself, you can use the following function.

def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                # nb elements[0:1] works in both string and list contexts
                yield perm[:i] + elements[0:1] + perm[i:]

Please note, in the above function we use yield keyword to work with generators, that consume less memory.

In this article, we have learnt how to generate all list permutations in Python.

Also read:

How to Sort List of Dictionaries by Value
How to Count Occurrence of List Item in Python
How to Restore Default Repositories in Ubuntu
How to Get Unique IP Address from Log File
How to Merge Two JS Objects

Leave a Reply

Your email address will not be published. Required fields are marked *