Search code examples
pythonpython-itertools

Calculating permutations without repetitions in Python


I have two lists of items:

A = 'mno'
B = 'xyz'

I want to generate all permutations, without replacement, simulating replacing all combinations of items in A with items in B, without repetition. e.g.

>>> do_my_permutation(A, B)
['mno', 'xno', 'mxo', 'mnx', 'xyo', 'mxy', 'xyz', 'zno', 'mzo', 'mnz', ...]

This is straight-forward enough for me to write from scratch, but I'm aware of Python's starndard itertools module, which I believe may already implement this. However, I'm having trouble identifying the function that implements this exact behavior. Is there a function in this module I can use to accomplish this?


Solution

  • Is this what you need:

    ["".join(elem) for elem in itertools.permutations(A+B, 3)]
    

    and replace permutations with combinations if you want all orderings of the same three letters to be collapsed down into a single item (e.g. so that 'mxo' and 'mox' do not each individually appear in the output).