Editor

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

string_permutations.py
def permutations(text):
# Base case: 0 or 1 characters can only be arranged one way
if len(text) <= 1:
return [text]
result = []
for i in range(len(text)):
first = text[i] # the character that goes first
rest = text[:i] + text[i + 1:] # all the other characters
# Recursive step: put first in front of every arrangement of rest
for perm in permutations(rest):
result.append(first + perm)
return result
word = "ABC" # or: word = input("Enter a string: ")
perms = permutations(word)
print("Permutations of", word)
for p in perms:
print(p)
print("Total:", len(perms))
Output
Permutations of ABC
ABC
ACB
BAC
BCA
CAB
CBA
Total: 6

How it works

  1. The base case is a string of 0 or 1 characters, which has only one arrangement, itself.
  2. 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.
  3. The recursive step finds every permutation of the remaining characters, and the program puts the chosen character in front of each one.
  4. For "ABC", A first with "BC" arranged gives ABC and ACB, B first gives BAC and BCA, and C first gives CAB and CBA.
  5. 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()

Using itertools.permutations()
from itertools import permutations
word = "ABC"
perms = ["".join(p) for p in permutations(word)]
print("Permutations:", perms)
print("Total:", len(perms))
Output
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

Words with repeated letters
from itertools import permutations
word = "AAB"
all_perms = ["".join(p) for p in permutations(word)]
unique = sorted(set(all_perms)) # drop the repeats
print("All arrangements:", len(all_perms))
print("Different ones:", unique)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises