0

Possible Duplicate:
All combinations of a list of lists

I've been trying to use python to add two lists of strings together and I can't get it work with the different arrangements of for loops that I've tried. What I have is two lists and I want to make a third list from the other two, so that index[0] from list 1 has all of the indexes from list 2 added to it in turn (each being a separate entry in the new list), and then the same for index[1] from list1, and so on..

snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]

resultlist = ["akatltd", "akarth", "akapef", "btbtltd", "btbrth", "btbpef", "wktltltd", "wktlrth", "wktlpef"]

I know the answer is simple but no matter what I do I keep get something that doesn't work at all, or it adds snippets1[0] to snippets2[0], snippets1[1] to snippets2[1] and so on. Help please!

Community
  • 1
  • 1
spikey273
  • 23
  • 3

3 Answers3

11
import itertools

snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]

resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
Oleh Prypin
  • 31,366
  • 9
  • 86
  • 97
3

You can try like this

resultlist=[]
for i in snipppets1:
 for j in snippets2:
  resultlist.append(i+j)
print resultlist
Vinil Narang
  • 653
  • 6
  • 11
3

And for completeness sake, I suppose I should point out the one liner not using itertools (but the itertools approach with product should be preferred):

[i+j for i in snippets1 for j in snippets2]
# ['akatltd', 'akarth', 'akapef', 'btbtltd', 'btbrth', 'btbpef', 'wktltltd', 'wktlrth', 'wktlpef']
Jon Clements
  • 132,101
  • 31
  • 237
  • 267