Python – Rows with K string in Matrix


When it is required to find rows, which have ‘K’ string in matrix, the ‘enumerate’ attribute, a simple iteration and ‘append’ method is used.

Example

Below is a demonstration of the same −

my_list = [["Pyt", "fun", "python"], ["python", "rock"],["Pyt", "for", "CS"], ["Keep", "learning"]]

print("The list is :")
print(my_list)

K = "Pyt"

my_result = []

for idx, element in enumerate(my_list):

   if K in element:
      my_result.append(idx)

print("The result is :")
print(my_result)

Output

The list is :
[['Pyt', 'fun', 'python'], ['python', 'rock'], ['Pyt', 'for', 'CS'], ['Keep', 'learning']]
The result is :
[0, 2]

Explanation

  • A list is defined and displayed on the console.

  • The value for K is defined.

  • An empty list is created.

  • The list is iterated over using the ‘enumerate’ attribute.

  • A condition is placed, which checks if ‘K’ is present as one of the elements of the list.

  • If yes, its index is appended to the empty list.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements