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?

2
  • 1
    Possible duplicate of How to generate all permutations of a list in Python Commented Sep 25, 2019 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. Commented Sep 25, 2019 at 20:02

2 Answers 2

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)))
Sign up to request clarification or add additional context in comments.

2 Comments

Remove the list(..) call. Its not needed with the map since permutations is an iterator and makes it so you have to iterate over the list twice. Also you are missing a ).
Thanks - edited. I moved the list call to the beginning since map would return an iterator in python 3.
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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.