Python | Ways to find all permutation of a string

Given a string, write a Python program to find out all possible permutations of a string. Let’s discuss a few methods to solve the problem.

Method #1: Using Naive Method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find all permutation of
# a given string
  
# Initialising string
ini_str = "abc"
  
# Printing initial string
print("Initial string", ini_str)
  
# Finding all permuatation
result = []
  
def permute(data, i, length): 
    if i == length: 
        result.append(''.join(data) )
    else
        for j in range(i, length): 
            # swap
            data[i], data[j] = data[j], data[i] 
            permute(data, i + 1, length) 
            data[i], data[j] = data[j], data[i]  
permute(list(ini_str), 0, len(ini_str))
  
# Printing result
print("Resultant permutations", str(result))

chevron_right


Output:



Initial string abc
Resultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']

 
Method #2: Using itertools

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find all permutation of
# a given string
  
from itertools import permutations
  
# Initialising string
ini_str = "abc"
  
# Printing initial string
print("Initial string", ini_str)
  
# Finding all permuatation
permutation = [''.join(p) for p in permutations(ini_str)]
# Printing result
print("Resultant List", str(permutation))

chevron_right


Output:

Initial string abc
Resultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.