3

Say I have random strings in Python:

>>> X = ['ab', 'cd', 'ef']

What I'd like to do is create all the permutations of the strings (not tuples), i.e.:

['abcdef', 'abefcd', 'cdabef', 'cdefab', 'efabcd', 'efcdab']

list(itertools.permutations(X)) outputs:

[('ab', 'cd', 'ef'), ('ab', 'ef', 'cd'), ('cd', 'ab', 'ef'), ('cd', 'ef', 'ab'), ('ef', 'ab', 'cd'), ('ef', 'cd', 'ab')]

I understand (I think) that due to needing mixed types, we need tuples instead of strings, but is there any way to work around this to get the strings?

Thanks much in advance?

Sebastian
  • 715
  • 6
  • 13
  • 1
    Possible duplicate of [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – Alex_P Sep 25 '19 at 19:55
  • 1
    @Alex_P Questionable duplicate. The OP already knows how to generate permutations using itertools. The OP is asking how to combine the result. Please make sure to read a question fully before flagging duplicates. Though this is probably a duplicate it is not a duplicate of that question. – Error - Syntactical Remorse Sep 25 '19 at 20:02

2 Answers2

1

You can use the string join function on the tuples you get to reduce them down to strings. This is made even easier with map, which can apply the same operation to every element in a list and return the list of altered items. Here's what it would look like:

list(map(lambda x: ''.join(x), itertools.permutations(X)))
Rob Streeting
  • 1,675
  • 3
  • 16
  • 27
1

Use join() to join the tuple of permutations as you consume to permutation iterator.

from itertools import permutations
X = ['ab', 'cd', 'ef']
result = [''.join(ele) for ele in permutations(X)]