Dkk
Dkk

Reputation: 63

print permutations of all strings in a list

I am trying to print the permutations of all the members in a list,but my script is printing the permutations of only last member of list i.e 'DMNCT'.

from itertools import permutations
element_all=['EESE', 'TTDT', 'SAIFE', 'DMNCT']
i=0
for i in range (len(element_all)):
    perms = [''.join(p) for p in permutations(element_all[i])]
print perms

It seems that my for loop is not working correctly.I am fairly new to python.Any help would be appreciated.

Upvotes: 0

Views: 61

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

This is happening because you're replacing perms each loop. You should define the list outside the loop and then extend it inside the loop.

from itertools import permutations
element_all=['EESE', 'TTDT', 'SAIFE', 'DMNCT']
perms = []
for i in element_all:
    perms.extend([''.join(p) for p in permutations(i)])
print perms

Or define the list all at once in a comprehension

perms = [''.join(p) for i in element_all for p in permutations(i)]

Upvotes: 2

Related Questions