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"]
Answers:
import itertools
snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]
resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
You can try like this
resultlist=[]
for i in snipppets1:
for j in snippets2:
resultlist.append(i+j)
print resultlist
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']
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"]
import itertools
snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]
resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
You can try like this
resultlist=[]
for i in snipppets1:
for j in snippets2:
resultlist.append(i+j)
print resultlist
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']