Finding all possible permutations of a given string in python

The itertools module has a useful method called permutations(). The documentation says:

itertools.permutations(iterable[, r])

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the
iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input
iterable is sorted, the permutation tuples will be produced in sorted
order.

You’ll have to join your permuted letters as strings though.

>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> perms

[‘stack’, ‘stakc’, ‘stcak’, ‘stcka’, ‘stkac’, ‘stkca’, ‘satck’,
‘satkc’, ‘sactk’, ‘sackt’, ‘saktc’, ‘sakct’, ‘sctak’, ‘sctka’,
‘scatk’, ‘scakt’, ‘sckta’, ‘sckat’, ‘sktac’, ‘sktca’, ‘skatc’,
‘skact’, ‘skcta’, ‘skcat’, ‘tsack’, ‘tsakc’, ‘tscak’, ‘tscka’,
‘tskac’, ‘tskca’, ‘tasck’, ‘taskc’, ‘tacsk’, ‘tacks’, ‘taksc’,
‘takcs’, ‘tcsak’, ‘tcska’, ‘tcask’, ‘tcaks’, ‘tcksa’, ‘tckas’,
‘tksac’, ‘tksca’, ‘tkasc’, ‘tkacs’, ‘tkcsa’, ‘tkcas’, ‘astck’,
‘astkc’, ‘asctk’, ‘asckt’, ‘asktc’, ‘askct’, ‘atsck’, ‘atskc’,
‘atcsk’, ‘atcks’, ‘atksc’, ‘atkcs’, ‘acstk’, ‘acskt’, ‘actsk’,
‘actks’, ‘ackst’, ‘ackts’, ‘akstc’, ‘aksct’, ‘aktsc’, ‘aktcs’,
‘akcst’, ‘akcts’, ‘cstak’, ‘cstka’, ‘csatk’, ‘csakt’, ‘cskta’,
‘cskat’, ‘ctsak’, ‘ctska’, ‘ctask’, ‘ctaks’, ‘ctksa’, ‘ctkas’,
‘castk’, ‘caskt’, ‘catsk’, ‘catks’, ‘cakst’, ‘cakts’, ‘cksta’,
‘cksat’, ‘cktsa’, ‘cktas’, ‘ckast’, ‘ckats’, ‘kstac’, ‘kstca’,
‘ksatc’, ‘ksact’, ‘kscta’, ‘kscat’, ‘ktsac’, ‘ktsca’, ‘ktasc’,
‘ktacs’, ‘ktcsa’, ‘ktcas’, ‘kastc’, ‘kasct’, ‘katsc’, ‘katcs’,
‘kacst’, ‘kacts’, ‘kcsta’, ‘kcsat’, ‘kctsa’, ‘kctas’, ‘kcast’,
‘kcats’]

If you find yourself troubled by duplicates, try fitting your data into a structure with no duplicates like a set:

>>> perms = [''.join(p) for p in permutations('stacks')]
>>> len(perms)
720
>>> len(set(perms))
360

Thanks to @pst for pointing out that this is not what we’d traditionally think of as a type cast, but more of a call to the set() constructor.

Leave a Comment