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
# 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
filter_none
Output:
Initial string abc Resultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
Method #2: Using itertools
# 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
filter_none
Output:
Initial string abc Resultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Recommended Posts:
- Find length of a string in python (4 ways)
- Python | Ways to find nth occurrence of substring in a string
- Python | Ways to split a string in different ways
- Python | Permutation of a given string using inbuilt function
- Reverse string in Python (5 different ways)
- Python | Ways to concatenate boolean to string
- Python | Ways to check if given string contains only letter
- Ways to remove i'th character from string in Python
- Python | Ways to check string contain all same characters
- Python | Ways to count number of substring in string
- Python | Ways to convert string to json object
- Python | Ways to remove n characters from start of given string
- Python | Ways to remove numeric digits from given string
- Python | Ways to convert list of ASCII value to string
- Python | Ways to sort letters of string alphabetically
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.



