Understanding Python Permutations function with examples

Permutations mean different orders by which elements can be arranged. The elements might be of a string, a list, or any other data type. It is the rearrangement of items in different ways. Python has different methods inside a package called itertools, which can help us achieve Python permutations

For example, if we have three balls – RED BLUE YELLOW 

We can make different arrangements for this ball. 

  • RED BLUE YELLOW  
  • RED YELLOW BLUE 
  • YELLOW RED BLUE 
  • YELLOW BLUE RED 
  • BLUE RED YELLOW 
  • BLUE YELLOW RED  

These all are possible arrangements where the order is essential, and there is no repetition, and this is known as permutation. 

Syntax of Python permutations

Python has a package called ‘itertools’ from which we can apply the permutations function to different data types. The number of total permutations possible is equal to the factorial of length (number of elements). In our case, as we have 3 balls, 3! = 3*2*1 = 6.  

To import permutations() – from itertools import permutations 

Parameters- 

  1. Iterable – Here, we have to pass the iterable of whose permutations we want. Examples of iterables- list, tuple, string, etc.   
  2. Size- In this parameter, we have to specify the number of elements in each permutation.

Example for Simple Python Permutation

from itertools import permutations 
a=permutations ([1,2,3],2) 
for i in a: 
  print(i) 
Output- 
(1, 2) 
(1, 3) 
(2, 1) 
(2, 3) 
(3, 1) 
(3, 2) 
python permutations

If we do not pass any argument in the second parameter, the default value is set as the length of the iterable. 

For example- 

from itertools import permutations 
a=permutations([1,2,3]) 
for i in a: 
   print(i) 
Output- 
(1, 2, 3) 
(1, 3, 2) 
(2, 1, 3) 
(2, 3, 1) 
(3, 1, 2) 
(3, 2, 1) 

You must be wondering why we are saving the result in a variable and printing the result using a ‘for’ loop. Let’s see what if we print the variable.  

from itertools import permutations 
a=permutations([1,2,3]) 
print(a) 
Output- 
<itertools.permutations object at 0x00000265E51F1360>  

We are getting this object as an output. So, we have to use a for loop to iterate through this variable and get the result.  

Another way to get the output is by making a list and then printing it. 

from itertools import permutations 
print(list(permutations([1,2,3]))) 
Output- 
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 

Using Python Permutations function on a String 

We can use the permutations function to find different orders in which a string can be arranged. Let us see how- 

string="ASHU" 
a=permutations(string) 
for i in list(a): 
   # join all the letters of the list to make a string 
   print("".join(i)) 
Output- 
ASHU 
ASUH 
AHSU 
AHUS 
AUSH 
AUHS 
SAHU 
SAUH 
SHAU 
SHUA 
SUAH 
SUHA 
HASU 
HAUS 
HSAU 
HSUA 
HUAS 
HUSA 
UASH 
UAHS 
USAH 
USHA 
UHAS 
UHSA 

If we want to order these elements in the group of two, we can do the following- 

string="ABC" 
a=permutations(string,2) 
for i in list(a): 
   # join all the letters of the list to make a string 
   print("".join(i)) 
Output- 
AB 
AC 
BA 
BC 
CA 
CB 

You can notice that the total number of results is equal to the factorial of the size we are giving to 2nd parameter. 

Find the order in lexicographical sorted order

If we want to find all the permutations of a string in a lexicographically sorted order, it means all the elements are arranged in alphabetical order, and if the first element is equal, then sorting them based on the next elements and so on. 

from itertools import permutations 
string,n = input(“Enter string and size”).split() 
print(*[''.join(i) for i in permutations(sorted(string),int(n))],sep='\n') 
Output 
Enter the string and size BAC 2 
AB 
AC 
BA 
BC 
CA 
CB 

Using Python permutations function on a list 

Now, if we want to find all the possible orders in which a list can be arranged, we can use a similar approach as we did for string. 

a=permutations([1,2,3,4],2) 
for i in a: 
   print(i) 
Output- 
(1, 2) 
(1, 3) 
(1, 4) 
(2, 1) 
(2, 3) 
(2, 4) 
(3, 1) 
(3, 2) 
(3, 4) 
(4, 1) 
(4, 2) 
(4, 3) 

We can also find the number of ways in which we can reorder the list using a single line of code- 

print(len(list(permutations([1,2,3,4],4)))) 
Output- 
24 

Python Permutation without built-in function for String

If we do not want to use the built-in function, we can make some functions to achieve this goal. 

answer=[] 
def permutation(string, i, length):   
   if i == length:   
        answer.append(''.join(string) )  
   else:   
       for j in range(i, length):   
           string[i], string[j] = string[j], string[i]   

          #keep increasing i by 1 till it becomes equal to 0 
            permutation(string, i + 1, length)   
           string[i], string[j] = string[j], string[i]   
permutation(list(string), 0, len(string))  
string="ABC" 
print(str(answer)) 
Output- 
['ABC', 'ACB', 'BAC', 'BCA', 'CBA', 'CAB'] 

Python Permutation without built-in function for Lists

def permutation(list1):  
   # If the length of list=0 no permuataions possible 
   if len(list1) == 0:  
       return []  
   # If the length of list=1, return that element 
   if len(list1) == 1:  
       return [list1]  
   l = []  
   for i in range(len(list1)):  
       m = list1[i]  
      # Extract list1[i] or m from the list. remlist1 is  
      # remaining list  
       remlist1 = list1[:i] + list1[i+1:]  
      # Generating all permutations where m is first  
      # element  
       for p in permutation(remlist1):  
            l.append([m] + p)  
   return l 
if __name__=="__main__": 
   print(list(permutation([1,2,3,4]))) 
Output- 
[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]] 

Must Read

Conclusion

There are some use cases or problem statements when we need to find all the possible orders in which elements can be arranged. So we use permutations from itertools. Some people get confused between combinations and Python permutations; in permutations, the order matters, but in combinations, the order doesn’t matter. 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments