Search code examples
python-3.xlistpython-itertools

Combine two lists by each element


I am new to python and want to combine/merge two lists by element like this:

Input

list = ['blue', 'red', 'green'] 
list2= ['trousers', 'shirt', 'pants'] 

Desired Output

desired list= ['blue trousers', 'blue shirt', 'blue pants', 'red trouser', 'red shirt', 'red pants',         'green trouser', 'green shirt', 'green pants']

I have researched stackoverflow and there came up the itertools library and the cartesian product. So I tried this:

from itertools import product 
  
def cartesian_product(arr1, arr2): 
  
    # return the list of all the computed tuple 
    # using the product() method 
    return list(product(arr1, arr2))  
    
# Driver Function  
if __name__ == "__main__":  
    arr1 = ['blue', 'red', 'green'] 
    arr2 = ['trouser', 'shirt', 'pants'] 
    print(cartesian_product(arr1, arr2)) 

This is the output which comes close (but packing the results into tuples instead of elements):

[('blue', 'trouser'), ('blue', 'shirt'), ('blue', 'pants'), ('red', 'trouser'), ('red', 'shirt'), ('red', 'pants'), ('green', 'trouser'), ('green', 'shirt'), ('green', 'pants')]

Any suggestion how I get to the desired output from there?


Solution

  • You could do it using the following technique (no use of itertools):

    list1 = ['blue', 'red', 'green'] 
    list2 = ['trousers', 'shirt', 'pants']
    desired_list = []
    
    for colour in list1:
        for garment in list2:
            desired_list.append(colour + ' ' + garment)
    

    For each element in the first list, this iterates through each element in the second list, giving the following output:

    ['blue trousers', 'blue shirt', 'blue pants', 'red trousers', 'red shirt',
    'red pants', 'green trousers', 'green shirt', 'green pants']
    

    Apologies if there is a more efficient way of doing this! I hope this helps.