Open In App

Python | Custom Multiplication in list of lists

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, when we are fed with the list of list, we need to multiply each of its element list with a particular element fed by the order in the other list. This particular problem is very specific but knowledge of it can be useful in such cases. Let’s discuss certain ways in which this can be done. 

Method #1: Using loops This is the Naive and brute force method perform this particular task in which we run a loop to get all the elements and it’s nested components and multiply accordingly. 

  1. Initialize a list of lists test_list containing 3 sublists.
  2. Initialize a list mult_list containing 3 integers.
  3. Print the original list test_list.
  4. Print the original multiply list mult_list.
  5. Initialize an empty list res containing 3 empty sublists.
  6. For each index i in test_list (range from 0 to 2):
    For each index j in mult_list (range from 0 to 2):
  7. Calculate the product of the value at index j in mult_list and the value at index j in the i-th sublist of test_list.
  8. Append the product to the i-th sublist of res.
  9. Print the resulting list res.

Python3




# Python3 code to demonstrate
# Custom Multiplication in list of lists
# Using loops
 
# initializing list
test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
 
# initializing multiply list
mult_list = [10, 20, 30]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing multiply list
print("The original multiply list : " + str(mult_list))
 
# using loops
# Custom Multiplication in list of lists
res = [[] for idx in range(len(test_list))]
for i in range(len(test_list)):
    for j in range(len(mult_list)):
        res[i] += [mult_list[i] * test_list[i][j]]
 
# print result
print("The list after multiply : " + str(res))


Output : 

The original list : [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
The original multiply list : [10, 20, 30]
The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(n^2), where n is the length of the inner list in the test_list.
Auxiliary space: O(n^2), where n is the length of the inner list in the test_list, since the result list res has the same size as test_list, and each element in res is a list with n elements. 

Method #2: Using list comprehension + enumerate() This problem can also be solved in a shorter way using the power of enumerate function to get the indices and value of the container at one time. This is one-liner approach to solve this problem. 

Python3




# Python3 code to demonstrate
# Custom Multiplication in list of lists
# Using list comprehension + enumerate()
 
# initializing list
test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
 
# initializing multiply list
mult_list = [10, 20, 30]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing multiply list
print("The original multiply list : " + str(mult_list))
 
# using list comprehension + enumerate()
# Custom Multiplication in list of lists
res = [[mult_list[i] * j for j in sub]
       for i, sub in enumerate(test_list)]
 
# print result
print("The list after multiply : " + str(res))


Output : 

The original list : [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
The original multiply list : [10, 20, 30]
The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(nm), where n is the number of sublists in the list and m is the length of each sublist.

Auxiliary space: O(nm), as we are creating a new list of the same size as the original list.

Method 3:  using the built-in zip() function 

  • Initialize an empty list named res.
  • Use the zip() function to iterate over the corresponding elements of the two lists, test_list and mult_list.
  • For each iteration, initialize an empty list named temp.
    • Use a for loop to iterate over the elements of the current sublist.
      • Multiply the current element of the sublist with the corresponding element in mult_list, and append the result to temp.
  • Print the final list with the multiplied values.

Python3




test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
mult_list = [10, 20, 30]
res = []
for sublist, mult in zip(test_list, mult_list):
    temp = []
    for elem in sublist:
        temp.append(elem * mult)
    res.append(temp)
print("The list after multiply : " + str(res))


Output

The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(n^2) because it uses nested loops to iterate over the elements of the input list. 
Auxiliary space: O(n) because it creates a new list to store the multiplied values.

Method #4: Using numpy library

Step-by-step approach:

  1. Import the numpy library
  2. Convert the given list of lists to a numpy array using the numpy.array() function.
  3. Convert the multiply list to a numpy array using the numpy.array() function.
  4. Use the numpy.multiply() function to multiply the numpy array of the test list with the numpy array of multiply list.
  5. Convert the resulting numpy array back to a list of lists using the tolist() function.
  6. Print the resulting list of lists.

Python3




import numpy as np
 
# initializing list
test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
 
# initializing multiply list
mult_list = [10, 20, 30]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing multiply list
print("The original multiply list : " + str(mult_list))
 
# using numpy library
# Custom Multiplication in list of lists
test_arr = np.array(test_list)
mult_arr = np.array(mult_list)
res_arr = np.multiply(test_arr, mult_arr.reshape(-1, 1))
res = res_arr.tolist()
 
# print result
print("The list after multiply : " + str(res))


Output:

The original list : [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
The original multiply list : [10, 20, 30]
The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(n^2) as it involves iterating over all elements in the list of lists.
Auxiliary space: O(n^2) as a new list of lists is created to store the result. In addition, numpy arrays are also created, which takes up additional space.

Method #5: Using the map() function

Step-by-step approach:

  • It uses the map() function to apply a lambda function to each sublist of test_list and multiply it with the corresponding integer from mult_list.
  • The lambda function takes two arguments, sub and mult, and returns a new list containing the products of the elements in sub and mult.
  • The map() function returns an iterator of the resulting lists, which are then converted back into a list using the list() function.
  • The resulting list is assigned to the variable res.
  • Finally, it prints the resulting list using the print() function and string concatenation.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Custom Multiplication in list of lists
# Using the map() function
 
# initializing list
test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
 
# initializing multiply list
mult_list = [10, 20, 30]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing multiply list
print("The original multiply list : " + str(mult_list))
 
# using the map() function
# Custom Multiplication in list of lists
res = list(map(lambda sub, mult: [i * mult for i in sub], test_list, mult_list))
 
# print result
print("The list after multiply : " + str(res))


Output

The original list : [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
The original multiply list : [10, 20, 30]
The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(n^2), where n is the number of elements in each sublist of test_list.
Auxiliary space: O(n^2), since a new list is created for each sublist in test_list

Method 6: Use the itertools module’s starmap() function. 

Step-by-step approach:

  • Import the itertools library using import itertools.
  • Initialize the test_list and mult_list as given in the code.
  • Use the zip() function to combine the sublists of test_list and the elements of mult_list.
  • Use the starmap() function from itertools to perform element-wise multiplication of the zipped pairs.
  • Convert the resultant map object back to a list using list() function.
  • Print the resultant list.

Below is the implementation of the above approach:

Python3




# importing the itertools module
import itertools
 
# initializing list
test_list = [[5, 6, 8], [7, 4, 3], [8, 10, 12]]
 
# initializing multiply list
mult_list = [10, 20, 30]
 
# using the itertools module's starmap() function
res = list(itertools.starmap(lambda sub, mult: [i * mult for i in sub], zip(test_list, mult_list)))
 
# print result
print("The list after multiply : " + str(res))


Output

The list after multiply : [[50, 60, 80], [140, 80, 60], [240, 300, 360]]

Time complexity: O(n^2) (due to the nested loop in lambda function)
Auxiliary space: O(n) (to store the resultant list)



Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads