PythonMastery
Python programs · Useful programs · intermediate

Find all permutations of a string in Python

List every ordering of the letters in a string, first with a recursive function, then with itertools.permutations, and handle repeated letters.

A permutation is one possible order of a set of items. The letters of "ABC" can be arranged in 6 orders. A string of n different letters has n! permutations (n × (n - 1) × ... × 1).

The program

python
def permutations(text):
    if len(text) <= 1:
        return [text]
    result = []
    for i, letter in enumerate(text):
        rest = text[:i] + text[i + 1:]
        for perm in permutations(rest):
            result.append(letter + perm)
    return result


print(permutations("ABC"))
print(len(permutations("ABCD")))
output
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
24

How it works

The function uses recursion:

For "ABC": A in front of "BC" and "CB", then B in front of "AC" and "CA", then C in front of "AB" and "BA".

The number of permutations grows very fast: 10 letters already give 3,628,800. Do not try to build the full list for long strings.

Another way: itertools.permutations

The standard library has this built in. It gives tuples of letters, so "".join() turns each one into a string. If letters repeat, as in "AAB", some orders are the same, and a set removes the copies:

python
from itertools import permutations

print(["".join(p) for p in permutations("ABC")])

all_orders = ["".join(p) for p in permutations("AAB")]
print(all_orders)
print(sorted(set(all_orders)))
output
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
['AAB', 'ABA', 'AAB', 'ABA', 'BAA', 'BAA']
['AAB', 'ABA', 'BAA']

permutations("ABC", 2) gives orders of only 2 letters at a time, such as ('A', 'B').

Learn the idea: Functions & Scoping, Itertools: Composable Iterator Building Blocks