pythonpython-3.10

Pairwise multiplication of elements between two lists


I am trying to calculate the product of every element from one list multiplied by every element from another list. from each list multiplied by each other.

For example, in list1 I have 4, which needs to be multiplied by 3 in list2. Next, the 4 in list1 needs to be multiplied by 1 in list2. The pattern continues until I receive the output: [12,4,36,8,6,2,18,4,21,7,63,14]. I haven't been able to achieve this -- here is the code I have so far:

def multiply_lists(list1,list2):
    for i in range(0,len(list1)):
        products.append(list1[i]*list2[i])
    return products

list1 = [4,2,7]
list2 = [3,1,9,2]
products = []
print ('list1 = ',list1,';','list2 = ', list2) 
prod_list = multiply_lists(list1,list2)
print ('prod_list = ',prod_list)

Solution

  • You're close. What you really want is two for loops so you can compare each value in one list against all of the values in the second list. e.g.

    def multiply_lists(list1, list2):
        for i in range(len(list1)):
            for j in range(len(list2)):
                products.append(list1[i] * list2[j])
        return products
    

    You also don't need a range col, you can directly iterate over the items of each list:

    def multiply_lists(list1, list2):
        for i in list1:
            for j in list2:
                products.append(i * j)
        return products
    

    And you could also do this as a comprehension:

    def multiply_lists(list1, list2):
        return [i * j for i in list1 for j in list2]