Python – Matrix Custom Multiplier

• Last Updated : 30 Dec, 2020

Sometimes, while working with data, we can have a problem in which we need to multiply each row of matrix with a different multiplier. This kind of application is important in data science domain. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + zip()
The combination of above functions can be used to perform this task. In this, we iterate through each row and perform the task of multiplication using zip().

 # Python3 code to demonstrate # Matrix Custom Multiplier# using loop + zip()  # Initializing listtest_list1 = [[1, 3], [5, 6], [8, 9]]test_list2 = [4, 3, 6]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Matrix Custom Multiplier# using loop + zip()res = []for mul, sub in zip(test_list2, test_list1):    temp = []    for ele in sub:        temp.append(mul * ele)    res.append(temp)  # printing result print ("Matrix after custom multiplication : " + str(res))
Output :
The original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]

Method #2 : Using list comprehension + zip()
The combination of above methods can be used to solve this problem. In this, we just iterate through the list and perform the task of multiplication in one liner.

 # Python3 code to demonstrate # Matrix Custom Multiplier# using list comprehension + zip()  # Initializing listtest_list1 = [[1, 3], [5, 6], [8, 9]]test_list2 = [4, 3, 6]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Matrix Custom Multiplier# using list comprehension + zip()res =  [[mul * ele for ele in sub] for mul, sub in zip(test_list2, test_list1)]  # printing result print ("Matrix after custom multiplication : " + str(res))
Output :
The original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]

My Personal Notes arrow_drop_up