VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-compare-two-numpy-arrays/

⇱ How to compare two NumPy arrays? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to compare two NumPy arrays?

Last Updated : 19 Sep, 2025

Sometimes you need to check if two arrays are same or compare their values. NumPy provides multiple ways to do this from simple equality checks to element-wise comparisons. Comparing arrays helps in:

  • Validating data correctness
  • Checking results of operations
  • Filtering or selecting data based on conditions

Let’s explore different methods to compare two arrays.

Using np.array_equal()

The array_equal() function is the simplest and most reliable way to compare two arrays. It checks whether:

  • Both arrays have the same shape
  • All elements are exactly the same

Syntax:

numpy.array_equal(arr1, arr2)

Example: This code compares two arrays using np.array_equal() and prints whether they are equal.


Output
Equal

Explanation: np.array_equal() returns True if arrays have the same elements and shape. It’s the cleanest and most reliable way to check equality.

Using == and .all()

This method first compares arrays element-wise using ==, then checks if all results are True with .all().

Example: This code uses element-wise comparison followed by .all() to decide if two arrays are fully equal.


Output
True

Explanation: Every element matches, so result is True. If even one element was different, it would return False.

Using Comparison Operators (>, <, >=, <=)

This method is not for equality checks, but for comparing values element by element. It helps when you want to know which array elements are greater/smaller.

Example: This code compares two arrays element by element using greater/less operators.


Output
Array a: [101 99 87]
Array b: [897 97 111]
a > b: [False True False]
a >= b: [False True False]
a < b: [ True False True]
a <= b: [ True False True]

Explanation: The result is a Boolean array, where each element shows the comparison result at that position. This is useful for conditional checks, not equality.

Comment