How to each item in list with all values of another list in Python

Question:

Given two lists like:

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

How can I 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? That is, the result should be

resultlist = ["akatltd", "akarth", "akapef", "btbtltd", "btbrth", "btbpef", "wktltltd", "wktlrth", "wktlpef"]
Asked By: spikey273

||

Answers:

import itertools

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

resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
Answered By: Oleh Prypin

You can try like this

resultlist=[]
for i in snipppets1:
 for j in snippets2:
  resultlist.append(i+j)
print resultlist
Answered By: Vinil Narang

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']
Answered By: Jon Clements
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.