Find Rows with given element in Matrix

By | November 29, 2024

Given a Matrix, get index of rows with K as elements.

Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], K = 6
Output : [0, 2]
Explanation : Matrix row number 0 and 2 have 6 as element. 

Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], K = 4
Output : [0, 1]
Explanation : Matrix row number 0 and 1 have 4 as element.

Method #1 : Using loop
In this, each row is iterated and K is checked in each row using in operator, if element is found, row number is appended in result.

# Python3 code to demonstrate working of
# Sublists with K 
# Using loop

# initializing list
test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]]
             
# printing original list
print("The original list is : " + str(test_list))

# initializing K 
K = 6

res = []

# loop is used for iterating rows
for sub in test_list :
    if K in sub:
        
        # index() computed the row index
        res.append(test_list.index(sub))

# printing result
print("Sublist index with K : " + str(res))

Output

The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]
Sublist index with K : [0, 2]

Method #2 : Using list comprehension + enumerate()
In this, index of required row is extracted using enumerate(). The list comprehension is used for iteration of rows.

# Python3 code to demonstrate working of
# Sublists with K 
# Using list comprehension + enumerate()

# initializing list
test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]]
             
# printing original list
print("The original list is : " + str(test_list))

# initializing K 
K = 6

# enumerate() is used to get row index
res = [idx for idx, sub in enumerate(test_list) if K in sub]

# printing result
print("Sublist index with K : " + str(res))

Output

The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]
Sublist index with K : [0, 2]
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.