numpy.subtract() in Python

Last Updated : 16 Feb, 2026

numpy.subtract() function is used to subtract one value or array from another. It performs element-wise subtraction, meaning each element of the second input is subtracted from the corresponding element of the first input. It works with scalars, lists and NumPy arrays and returns the result as a new array or scalar.

Example: This code subtracts two numbers using numpy.subtract(). It returns a single scalar value as result.

Python
import numpy as np

a = 15
b = 5

r = np.subtract(a, b)
print(r)

Output
10

Explanation: np.subtract(a, b) subtracts b from a.

Syntax

numpy.subtract(x1, x2, out=None, where=True, dtype=None)

Parameters:

  • x1: First input (array or scalar).
  • x2: Second input (array or scalar) to subtract from first.
  • out (optional): Stores the result in an existing array.
  • where (optional): Condition to apply subtraction.
  • dtype (optional): Defines the data type of result.

Return: Returns an array or scalar containing the subtraction result.

Examples

Example 1: This code performs element-wise subtraction between two one-dimensional arrays of same size.

Python
import numpy as np

a = np.array([5, 10, 15])
b = np.array([1, 2, 3])

r = np.subtract(a, b)
print(r)

Output
[ 4  8 12]

Explanation: np.subtract(a, b) subtracts each element of b from a.

Example 2: This code subtracts elements of two matrices having same shape.

Python
import numpy as np

a = np.array([[8, 6], [4, 2]])
b = np.array([[1, 2], [3, 4]])

r = np.subtract(a, b)
print(r)

Output
[[ 7  4]
 [ 1 -2]]

Explanation: np.subtract(a, b) performs subtraction for each matrix position.

Example 3: This code subtracts a single number from every element of an array.

Python
import numpy as np

a = np.array([10, 20, 30])
r = np.subtract(a, 5)
print(r)

Output
[ 5 15 25]

Explanation: np.subtract(a, 5) subtracts 5 from each element of a.

Example 4: This code stores the subtraction result in an existing array using out.

Python
import numpy as np

a = np.array([9, 8, 7])
b = np.array([1, 2, 3])
o = np.empty(3, dtype=int)

np.subtract(a, b, out=o)
print(o)

Output
[8 6 4]

Explanation: out=o stores the result in array o instead of creating new array.

Comment