I have two lists, say firstList = ['a','b','c']
and secondList = [1,2,3,4]
.
I have to make a list of tuples by merging these lists in such a way that output should be like this
[('a',1),('a',2),('a',3),('a',4),('b',1), ('b',2) .....]
One simple way to do this is by
outputList = []
for i in firstList:
for j in secondList:
outputList.append((i,j))
How can I do this more simply?
>>> firstList = ['a','b','c']
>>> secondList = [1,2,3,4]
>>> from itertools import product
>>> list(product(firstList, secondList))
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]
Also here's a nicer version of your for loops using a list comprehension:
>>> [(i, j) for i in firstList for j in secondList]
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]