NumPy multiply()

The multiply() function is performs element-wise multiplication of two arrays.

import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

# perform element-wise multiplication between array1 and array2 result = np.multiply(array1, array2)
print(result) # Output : [ 4 10 18]

multiply() Syntax

The syntax of multiply() is:

numpy.multiply(array1, array2, out=None)

multiply() Arguments

The multiply() function takes following arguments:

  • array1 and array2 - two input arrays to be multiplied element-wise
  • out (optional) - the output array where the result will be stored

Note: array1 and array2 must have the same shape unless one of them is a scalar value.


multiply() Return Value

The multiply() function returns an array that contains the result of element-wise multiplication between the input arrays.


Example 1: Multiply Two Arrays

import numpy as np

array1 = np.array([10, 20, 30])
array2 = np.array([2, 4, 6])

# perform element-wise multiplication between arrays array1 and array2 result = np.multiply(array1, array2)
print(result)

Output

[ 20  80 180]

Example 2: Multiplication of an Array by a Scalar

import numpy as np

array1 = np.array([1, 2, 3])
scalar = 2

# multiply each element in array1 by the scalar value result = np.multiply(array1, scalar)
print(result)

Output

[2 4 6]

In this example, we multiplied each element in array1 by the scalar value of 2.


Example 3: Use out to Store Result in a Desired Array

import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

# create an empty array with the same shape as array1 and array2
result = np.zeros_like(array1)

# perform element-wise multiplication of array1 and array2 and store the result in result np.multiply(array1, array2, out=result)
print(result)

Output

[ 4 10 18]

Here, after specifying out=result, the result of element-wise multiplication of array1 and array2 is stored in the result array.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community