Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use np.subtract() for a 2D array in Python

Maria Elijah


The Python library Numpy provides us with a method called subtract(). We use this to subtract two arrays.

The numpy.subtract() method

​​The numpy.subtract() method returns the element-wise (element by element) difference between two arrays.

We can create a two-dimensional (2D) array using a list of lists in Python.


numpy.subtract(A, B, dtype=None, out=None)


  • A: This is the first input array.
  • B: This is the second input array.
  • dtype: This is an optional parameter. It represents the return type of the array.
  • out: This is an optional parameter. It represents the alternative output array where the result is to be placed.

Note: If A and B have distinct shapes, they must be able to be broadcasted to a common shape for output representation.

Return value

The numpy.subtract() method returns the difference between two input arrays, element-wise.

If the out parameter is specified, this method returns an array reference to out.


The following code shows how to use np.subtract() for 2D arrays.

# Import numpy.
import numpy as np
# Create two 2D arrays.
A = np.array([[2,6,5],[3,4,8]])
B = np.array([[1,7,2],[10,9,4]])

# Find the difference between the 2D arrays.
# Store the result in arr_diff. 
arr_diff = np.subtract(A, B)

Using np.subtract() for 2D arrays in Python


  • Line 2: We import the numpy library.
  • Line 4–5: We create two 2D arrays, A and B.
  • Line 9: We use the np.subtract() method to find the difference between the x1 and x2 arrays. The result is stored in a new variable called arr_diff.
  • Line 11: We display the result to the console.



View all Courses

Keep Exploring