Sebastian
Sebastian

Reputation: 795

Permutations into lists in python

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?

Upvotes: 3

Views: 121

Answers (2)

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)]

Upvotes: 1

Rob Streeting
Rob Streeting

Reputation: 1735

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)))

Upvotes: 1

Related Questions