Open In App

Check Whether a Numpy Array contains a Specified Row

Last Updated : 19 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In NumPy, you may need to check if a given list exists as a row in an array. If the list matches a row exactly (same values, same order), result is True. Otherwise, it is False.

This can be done by converting the array to a list of lists using tolist() and checking with the in operator.

Example: This code creates a small 2D NumPy array and checks if a given list is present as one of its rows.

Python
import numpy as np
arr = np.array([[1, 2],
                [3, 4]])
row = [3, 4]
print(row in arr.tolist())

Output
True

Syntax

ndarray.tolist()

  • Parameters: None -> tolist() does not take any parameters.
  • Returns: A nested Python list containing all array elements.

Examples

Example 1: This example shows how to test multiple lists against a larger NumPy array. Each list is checked row by row.

Python
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
                [6, 7, 8, 9, 10],
                [11, 12, 13, 14, 15],
                [16, 17, 18, 19, 20]])

print("Array:\n", arr)
print([1, 2, 3, 4, 5] in arr.tolist())     
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())    
print([11, 12, 13, 14, 15] in arr.tolist()) 

Output
Array:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
True
False
False
True

Example 2: Suppose you have a dataset of student marks, and you want to check if a particular student’s record exists.

Python
import numpy as np
marks = np.array([[85, 90, 92],
                  [70, 65, 80],
                  [95, 88, 91]])

student = [70, 65, 80]
print(student in marks.tolist())

Output
True

This shows how row checking can be applied to real datasets like student marks, employee details, or sensor readings.

Alternative Method: Using numpy.any()

Another way to check if a row exists in a NumPy array is by using NumPy’s built-in comparison functions instead of converting the array to a Python list. This approach is more efficient for large arrays and keeps the operation within NumPy itself.

Example: This code checks whether the row [3, 4] exists in a 2D NumPy array using np.all() and np.any().

Python
import numpy as np
arr = np.array([[1, 2],
                [3, 4]])

row = [3, 4]
print(np.any(np.all(arr == row, axis=1)))

Output
True

Explore