Search code examples
pythonlistpython-itertoolscartesian-product

How can I make a list of tuples from two source lists, matching each possible element from the first to an element from the second?


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?


Solution

  • >>> 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)]