Python Program to Print All Permutations of a String
Intermediate · Recursion
A permutation is one way of arranging items in order. The string "ABC" has 6 permutations, ABC, ACB, BAC, BCA, CAB and CBA, and in general a string of n different characters has n! of them. This program finds them with recursion: pick each character to go first, then arrange the rest.
Program
Permutations of ABC ABC ACB BAC BCA CAB CBA Total: 6
How it works
- The base case is a string of 0 or 1 characters, which has only one arrangement, itself.
- For a longer string, the loop picks each character in turn to go first, and
text[:i] + text[i + 1:]is the string with that character taken out. - The recursive step finds every permutation of the remaining characters, and the program puts the chosen character in front of each one.
- For "ABC", A first with "BC" arranged gives ABC and ACB, B first gives BAC and BCA, and C first gives CAB and CBA.
- A string of n different characters has n! permutations, so 4 characters give 24 and 10 characters already give 3,628,800.
Other ways to write it
Using itertools.permutations()
Permutations: ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] Total: 6
itertools.permutations() gives each arrangement as a tuple of characters, like ("A", "B", "C"), so "".join(p) turns it back into a string.
Words with repeated letters
All arrangements: 6 Different ones: ['AAB', 'ABA', 'BAA']
When a letter repeats, some arrangements look the same, because swapping the two As changes nothing, so a set keeps one copy of each and leaves 3 different permutations.
Try it yourself
Change word to "ABCD" and check that the total is 24.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises