Open In App

Search Elements in a Matrix - Python

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]], the task would be to check if an element like 13 is present. The result would be True if found, or False if the element does not exist within the matrix.

Using list comprehension

any() is a built-in Python function that checks if any element in an iterable evaluates to True. When combined with list comprehension, it allows us to check if an element exists in any of the sublists in a nested list or matrix .

Python
a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]]

res = any(13 in sub for sub in a)
print(str(res))

Output
True

Explanation: any(13 in sub for sub in a) checks if 13 is present in any row of the matrix a. It uses a generator expression with any(), which returns True as soon as 13 is found.

Using numpy

NumPy is a powerful library for numerical computations . It provides a highly efficient way to work with large matrices due to vectorized operations. This eliminates the need for explicit loops, making operations faster and easier to write.

Python
import numpy as np

# Create a 2D NumPy array 
a = np.array([[4, 5, 6], [10, 2, 13], [1, 11, 18]])

res = np.any(a == 13)
print(res)

Output
True

Explanation: np.any(a == 13) checks if 13 exists in the NumPy array a. The expression (a == 13) creates a boolean array and np.any() returns True if at least one True value is found, ensuring an efficient search.

Using itertools.chain

itertools.chain function from itertools module that takes multiple iterables and combines them into a single iterable. This is useful when we want to flatten a matrix and perform operations on all elements without explicitly nesting loops.

Python
import itertools
a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]]

res = 19 in itertools.chain(*a)
print(str(res))

Output
False

Explanation: 19 in itertools.chain(*a) flattens the 2D list a and checks if 19 is present in the flattened sequence, offering a efficient way to search for the element.

Using for loop

This is the most explicit method, where we manually iterate through the matrix using a nested for loop. It checks each row to see if the target element is present and exits early once a match is found.

Python
a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]]
found = False # Initialize a variable 'found'

for row in a:
    if 19 in row:
        found = True
        break
print(str(found))

Output
False

Explanation: for loop iterates through each row of the matrix a. If 19 is found in a row, found is set to True and the loop exits early with break.


Next Article

Similar Reads