The multiplication of two equal size lists multiplies each element from one list by the element at the same index in the other list.
For example, the multiplication of [1, 2, 3, 4]
and [2, 0, 3, 2]
results in [2, 0, 9, 8]
.
In Python, you can multiply two lists using one of the following ways.
Use zip() to Multiply Two List
Pass the two lists as arguments to the zip(list1, list2)
method to create a list of tuples that pair elements with the same position from both lists, then iterate through the new list to multiply the elements of each pair and append them to the product list.
list1 = [1, 2, 3, 4]
list2 = [2, 0, 3, 2]
product = []
for x, y in zip(list1, list2):
product.append(x*y)
print(product)
Output: [2, 0, 9, 8]
Another way to do this is to use list comprehension as follows:
list1 = [1, 2, 3, 4]
list2 = [2, 0, 3, 2]
print([x*y for x,y in zip(list1, list2)])
Use numpy.multiply() to multiply Two list
Use the multiply()
method of the numpy library to multiply two lists.
import numpy
list1 = [1, 2, 3, 4]
list2 = [2, 0, 3, 2]
product = numpy.multiply(list1, list2)
print(product)
Output: [2 0 9 8]
Use map() to multiply Two list
Call the built-in map()
function, with two lists as iterables and lambda x, y: x*y
as function and convert the returned map object into a list using the list()
constructor.
list1 = [1, 2, 3, 4]
list2 = [2, 0, 3, 2]
product = list(map(lambda x, y: x*y, list1, list2))
print(product)
Output: [2, 0, 9, 8]