How to Get all the Permutations of String in Python using itertools?

Till now I have shared many Python programming examples. I am little surprised as I missed to write about permutations even though it is very popular.

For an instance, you have to accomplish 5 jobs. You can execute these jobs in any order as you find productive. To find the best order, you have to get all the possible orders of Job. By comparing all those possible orders you can choose best one. So the ordering of the jobs here is nothing but the permutation.

Let’s see…

What is Permutation?

The permutation is nothing but the rearrangement of the elements in the set out of all possible orders.

Let’s take a string. It is a set of characters (letters).

If you have string ‘ABCD’; ‘BACD’, ‘ABDC’… are the permutations.

The number of permutation for the given set= n! (factorial of n)

– Where n is a number of elements in the given set.

In above example, the length of string ‘ABCD’ is 4. The number of permutation possible with this string is 4! = 24.

Getting all the Permutations of String in Python Program:

For permutations, we can use backtracking technique. But if you are using Python, we have an inbuilt module to generate all valid permutations for the given object.

In this article, I will share a simple line of code to generate all the permutations of the string.

It’s not difficult as Python is ever mean to be the easiest language to learn.

You can use existing Python module named itertools. This module comes with function permutations(). With this function, it is pretty easy to get all the permutations of string in Python.

I am complete Python Nut, love Linux and vim as an editor. I hold Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack Portal.