Open In App

Python – Multiply all cross list element pairs

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we need to perform the multiplication of each element of list with another list. This can have applications in both web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Method #1: Using list comprehension This is the most straightforward method to perform this task. In this, we iterate both the list and perform multiplication of each element with others and store the result in the new list. 

Python3




# Python3 code to demonstrate
# Multiply all cross list element pairs
# using list comprehension
 
# Initializing lists
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Multiply all cross list element pairs
# using list comprehension
res = [i * j for j in test_list1 for i in test_list2]
             
# printing result
print ("The multiplication list is : " + str(res))


Output : 

The original list 1 is : [4, 5, 6]
The original list 2 is : [6, 4, 2]
The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]

Time complexity: O(n^2)
Auxiliary space: O(n^2) 

Method #2 : Using product() This is another way in which this task can be performed. In this, we perform the task of multiplication using product(). 

Python3




# Python3 code to demonstrate
# Multiply all cross list element pairs
# using product()
from itertools import product
 
# Initializing lists
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Multiply all cross list element pairs
# using product()
res = [a * b for a, b in product(test_list1, test_list2)]
             
# printing result
print ("The multiplication list is : " + str(res))


Output : 

The original list 1 is : [4, 5, 6]
The original list 2 is : [6, 4, 2]
The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]

Time complexity: O(n^2), where n is the length of the input lists.
Auxiliary space: O(n^2). The result list (res) contains n^2 elements, which is the maximum possible number of pairs between the two input lists. Therefore, the space required to store the result is proportional to n^2.

Method#3: Using nested For loop method.

Step by step approach:

  1. Define a function named “multiply_pairs” that takes in two lists named “test_list1” and “test_list2”, and an optional parameter named “res” that defaults to an empty list.
  2. Check if either of the input lists is empty, if so, return the “res” list.
  3. If both input lists are non-empty, create two nested loops. The outer loop iterates over each element of “test_list1”, and the inner loop iterates over each element of “test_list2”.
  4. For each pair of elements in the two input lists, multiply them and append the result to the “res” list.
  5. Return the “res” list.
  6. Initialize two lists named “test_list1” and “test_list2” with some integer values.
  7. Print the original values of the two lists.
  8. Call the “multiply_pairs” function with the two input lists as arguments, and store the result in a variable named “res”.
  9. Print the final multiplication list “res”.

Python3




def multiply_pairs(test_list1, test_list2, res=[]):
    if not test_list1 or not test_list2:
        return res
    for i in test_list1:
        for j in test_list2:
            res.append(i * j)
    return res
 
# Initializing lists
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Multiply all cross list element pairs
res = multiply_pairs(test_list1, test_list2)
 
# printing result
print("The multiplication list is : " + str(res))
#this code contributed by tvsk


Output

The original list 1 is : [4, 5, 6]
The original list 2 is : [6, 4, 2]
The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Method #4: Using Recursion

Here’s the step by step algorithm for the code that uses recursion:

  1. Define the function multiply_pairs that takes in two lists as arguments, list1 and list2, and a result list res which is initialized to an empty list.
  2. Check if either of the input lists is empty. If yes, return the result list.
  3. If both lists are non-empty, pop the first element from the first list and call it num1, and pop the first element from the second list and call it num2.
  4. Multiply num1 and num2 and append the result to the result list res.
  5. Recursively call the multiply_pairs function with the updated lists list1 and list2, and the updated result list res.
  6. Return the result list res.

Python3




def multiply_pairs(test_list1, test_list2):
    if not test_list1 or not test_list2:
        return []
    return [test_list1[0] * x for x in test_list2] + multiply_pairs(test_list1[1:], test_list2)
 
# Initializing lists
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Multiply all cross list element pairs
res = multiply_pairs(test_list1, test_list2)
 
# printing result
print("The multiplication list is : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list 1 is : [4, 5, 6]
The original list 2 is : [6, 4, 2]
The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]

Time complexity:
The time complexity of this algorithm is O(n^2), where n is the length of the input lists. This is because in the worst case scenario, each element in list1 will be multiplied with each element in list2.

Space complexity:
The space complexity of this algorithm is also O(n^2), where n is the length of the input lists. This is because the result list res will contain n^2 elements in the worst case scenario. Additionally, each recursive call to the multiply_pairs function will create a new stack frame, so the space complexity is also dependent on the maximum recursion depth, which is O(n) in this case.

Method #5: Using numpy:

Algorithm :

1. Import the numpy module.
2.Initialize two arrays arr1 and arr2 using the np.array() method.
3. Print the original arrays using print() method.
4. Use the np.multiply.outer() method to get the outer product of two arrays.
5.Convert the resultant 2D array into a 1D array using the ravel() method.
6. Print the resultant array using print() method.
7. End of the program.

Python3




import numpy as np
 
# Initializing arrays
arr1 = np.array([4, 5, 6])
arr2 = np.array([6, 4, 2])
 
# printing original arrays
print("The original array 1 is : ", arr1)
print("The original array 2 is : ", arr2)
 
# Multiply all cross array element pairs
res = np.multiply.outer(arr1, arr2).ravel()
 
# printing result
print("The multiplication array is : ", res)
#This code is contributed by Jyothi pinjala


Output: 

The original array 1 is :  [4 5 6]
The original array 2 is :  [6 4 2]
The multiplication array is :  [24 16  8 30 20 10 36 24 12]

The time complexity:O(n^2), where n is the length of the lists. This is because it uses a recursive approach to iterate over the lists and compute the product of all possible pairs.

The space complexity: O(n^2), as the method creates a new list to store the result of each multiplication and recurses until all pairs have been computed. This means that as the length of the lists grows, so does the memory required to store the intermediate results.

Method: Iterative approach using a single for loop

Steps:

  1. Initialize an empty list to store the multiplication result.
  2. Iterate through the first list, test_list1.
  3. Within the first loop, iterate through the second list, test_list2.
  4. Multiply the current element from test_list1 with the current element from test_list2 and append the result to the multiplication list.
  5. Return the multiplication list.

Python3




def multiply_lists(test_list1, test_list2):
    multiplication_list = []
    for i in test_list1:
        for j in test_list2:
            multiplication_list.append(i * j)
    return multiplication_list
 
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
multiplication_list = multiply_lists(test_list1, test_list2)
print("The original list 1 is :", test_list1)
print("The original list 2 is :", test_list2)
print("The multiplication list is :", multiplication_list)


Output

The original list 1 is : [4, 5, 6]
The original list 2 is : [6, 4, 2]
The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]

Time complexity: O(n^2), where n is the length of the input lists. 

Auxiliary space: O(n^2), where n is the length of the input lists. 

Method: Using map and lambda functions to multiply all cross-list element pairs.

Steps:

  1. Use the map function to iterate over each element of test_list1.
  2. Within the map function, use a lambda function to multiply each element of test_list1 with each element of test_list2.
  3. Use the list function to convert the map object into a list and return it.

Python3




# Python program for the above approach
 
# Function to muultiple the two list using
# map and lambda function
def map_lambda_multiply(test_list1, test_list2):
    result = list(
        map(lambda x: list(map(lambda y: x*y, test_list2)), test_list1))
    return [elem for sublist in result for elem in sublist]
 
# Driver Code
test_list1 = [4, 5, 6]
test_list2 = [6, 4, 2]
 
print(map_lambda_multiply(test_list1, test_list2))


Output

[24, 16, 8, 30, 20, 10, 36, 24, 12]

Time Complexity: O(N2) where n is the length of the input lists.
Auxiliary Space: O(N2) to store the multiplication results in the result list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads