np.multiply(a, b) multiplies each element of a by the corresponding element of b, following the usual broadcasting rules — this is often called the Hadamard product in a linear algebra context, to distinguish it explicitly from matrix multiplication. This distinction matters a lot in NumPy specifically: * always means element-wise multiplication for ndarrays, while actual matrix multiplication uses the separate @ operator or np.matmul(), and mixing the two up is one of the most common sources of subtle bugs when translating math notation into NumPy code.
1Understanding np.multiply()
np.multiply(a, b) multiplies each element of a by the corresponding element of b, following the usual broadcasting rules — this is often called the Hadamard product in a linear algebra context, to distinguish it explicitly from matrix multiplication. This distinction matters a lot in NumPy specifically: * always means element-wise multiplication for ndarrays, while actual matrix multiplication uses the separate @ operator or np.matmul(), and mixing the two up is one of the most common sources of subtle bugs when translating math notation into NumPy code.
Never use * expecting matrix multiplication in NumPy — it always multiplies element-wise, broadcasting shapes as needed; use @ or np.matmul() specifically when you mean actual matrix multiplication.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.multiply(a, b))2Practical Example
Here is a real-world application of np.multiply() showing how it is used in production NumPy code.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[1, 0], [0, 1]])
print(A * B)
print(A @ B)3Best Practices
Follow these guidelines when working with np.multiply():
1. Use * (or np.multiply()) only for element-wise multiplication, and @ (or np.matmul()) for true matrix multiplication — never assume they're interchangeable
2. Double-check array shapes before relying on broadcasting in a multiplication, since a shape mismatch can silently produce an unexpected result rather than always raising an error
3. Use np.multiply(a, b, out=result) when writing into a pre-allocated array matters for memory efficiency in a hot loop
Tip: Never use * expecting matrix multiplication in NumPy — it always multiplies element-wise, broadcasting shapes as needed; use @ or np.matmul() specifically when you mean actual matrix multiplication.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.multiply(a, b))