Understanding Permutations Python Function [With Examples]

Permutations Python Function – The term “permutations” refers to the many ways in which components can be organized. The items might be strings, lists, or any other sort of data. It is the rearranging of objects in various ways. Python has a package called itertools that contains various methods for achieving 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

A permutation is a term used to describe a set of potential configurations in which the order is important and there is no repetition.

Syntax of python permutations

We may utilize the permutations function and apply it to various data types using Python’s ‘itertools‘ module. The entire number of permutations is equal to the length factorial (number of elements). Because we have three balls, 3! = 321 = 6.

To import permutations() – from itertools import permutations

Parameters:

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

Examples for Simple Python Permutation

In this section we will try different examples:

Example 01: Passing argument as the second parameter

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

Output:

Permutations Python Function img1

Example 02: Without Passing any argument

from itertools import permutations 
a=permutations ([1,2,3]) 
for i in a: 
  print(i) 
Permutations Python Function img2

You’re probably asking why we’re saving the result in a variable and then printing it with a ‘for’ loop. Let’s have a look at what happens if we print the variable.

Example 03: Printing result without for loop

from itertools import permutations 
a=permutations([1,2,3]) 
print(a) 

Output:

Permutations Python Function img3

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.

Example 04: 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:

Permutations Python Function img4

Using Python Permutations function on a String

The permutations function can be used to find different orders in which a string can be arranged. Let’s see how it goes.

Example 05:

from itertools import permutations 
string="SOFT"
a=permutations(string) 
for i in list(a): 
   # join all the letters of the list to make a string 
   print("".join(i)) 
Permutations Python Function img5

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

Example 06:

from itertools import permutations 
string="SOFT"
a=permutations(string,2) 
for i in list(a): 
   # join all the letters of the list to make a string 
   print("".join(i)) 

Output:

Permutations Python Function img6

Find the order in lexicographical sorted order

If we wish to locate all the permutations of a string in a lexicographically sorted manner. We must first organize all of the components in alphabetical order. Then sort them depending on the following elements, and so on.

Example 07:

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:

img7

Using python permutations function on a list 

Now, we can apply the same method. We used for the string to identify all the potential orders. In which a list may be ordered.

Example 08:

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

Output:

img8

We can also see how many different ways. We can reorganize the list with only one line of code. see the below example:

Example 09:

from itertools import permutations
print(len(list(permutations([1,2,3,4],4)))) 

Output:

img9

Python Permutation without built-in function [itertools] for String

We can construct our own function to achieve this purpose. If we don’t want to utilize the built-in function.

Example 10:

# Recursive function to generate all permutations of a string
def permutations(remaining, candidate=''):
 
    if len(remaining) == 0:
        print(candidate)
 
    for i in range(len(remaining)):
 
        newCandidate = candidate + remaining[i]
        newRemaining = remaining[0:i] + remaining[i+1:]
 
        permutations(newRemaining, newCandidate)
 
if __name__ == '__main__':
 
    s = 'ABC'
    permutations(s)

Output:

img10

Python Permutation without built-in function [itertools] for Lists

Example 11:

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:

img11

That’s all for this article. If you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. List in Python [With Examples]
  2. Python Strings with Examples
  3. Python Tuple [With Examples]
  4. How to plot Python Treemap
  5. How to read JSON in Python

2 thoughts on “Understanding Permutations Python Function [With Examples]”

  1. Do you mind if I quote a couple of your articles as long as I provide
    credit and sources back to your webpage? My blog is in the exact same niche
    as yours and my users would truly benefit from a lot of
    the information you present here. Please let me know if this is okay with you.
    Thanks!

    Reply

Leave a Comment