ID : 318

viewed : 64

Tags : PythonPython List

98

This tutorial will demonstrate various methods to perform element-wise multiplication of two lists in Python. Suppose we have two lists of integers with the same dimensions and we want to multiply elements of the first list with the elements at the same position in the second list and get a resultant list with the same dimensions.

`zip()`

MethodThe built-in `zip()`

method in Python takes one or more iterables and aggregates the iterables into a tuple. Like the lists `[1,2,3]`

and `[4,5,6]`

will become `[(1, 4), (2, 5), (3, 6)]`

. Using the `map()`

method, we access both lists element-wise and get the required list using the list comprehension method.

The below code example shows how to multiple 1D and 2D lists using `zip()`

with the list comprehension.

`list1 = [2,4,5,3,5,4] list2 = [4,1,2,9,7,5] product = [x*y for x,y in zip(list1,list2)] print(product) `

Output:

`[8, 4, 10, 27, 35, 20] `

Multiplication of 2D Lists:

`list1 = [[2,4,5],[3,5,4]] list2 = [[4,1,2],[9,7,5]] product = [[0]*3]*2 for x in range(len(list1)): product[x] = [a*b for a,b in zip(list1[x],list2[x])] print(product) `

Output:

`[[8, 4, 10], [27, 35, 20]] `

`numpy.multiply()`

MethodThe `multiply()`

method of the `NumPy`

library in Python, takes two arrays/lists as input and returns an array/list after performing element-wise multiplication. This method is straightforward, as we do not have to do any extra work for 2D multiplication, but the negative point of this method is that it canâ€™t be used without the `NumPy`

library.

The below code examples demonstrates how to multiply 1D and 2D lists in Python using the `numpy.multiply()`

method.

- 1D multiplication:

`import numpy as np list1 = [12,3,1,2,3,1] list2 = [13,2,3,5,3,4] product = np.multiply(list1,list2) print(product) `

Output:

`[156 6 3 10 9 4] `

- 2D multiplication:

`import numpy as np list1 = [[12,3,1],[2,3,1]] list2 = [[13,2,3],[5,3,4]] product = np.multiply(list1,list2) print(product) `

Output:

`[[156 6 3] [ 10 9 4]] `

`map()`

FunctionThe `map`

function takes a function and one or more iterables as input and returns an iterable applying the provided function on the input lists.

We can perform 1D and 2D element-wise multiplication of two lists in Python using the `map()`

function by passing both lists as the arguments to the `map()`

function. The below code examples demonstrate how we can use the `map()`

to multiply two Python lists.

Example code for 1D multiplication:

`list1 = [2,4,5,3,5,4] list2 = [4,1,2,9,7,5] product = list(map(lambda x,y: x*y ,list1,list2)) print(product) `

Output:

`[8, 4, 10, 27, 35, 20] `

Example code for 2D multiplication:

`list1 = [[2,4,5],[3,5,4]] list2 = [[4,1,2],[9,7,5]] product = [[0]*3]*2 for x in range(len(list1)): product[x] = list(map(lambda a,b: a*b ,list1[x],list2[x])) print(product) `

Output:

`[[8, 4, 10], [27, 35, 20]] `