Print Rows from Matrix with Same Element at Given Index in Python



When it is required to print the rows from the matrix that have the same element at the given index, a list comprehension and the ‘all’ operator is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]

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

my_key = 1
print("The key is ")
print(my_key)

my_result = [element for element in my_list if all(str(i)[my_key] == str(element[0])[my_key] for i in element)]

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

Output

The list is :
[[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]]
The key is
1
The result is :
[[7745, 6755, 87, 978], [192, 997, 49]]

Explanation

  • A list of list is defined and is displayed on the console.

  • The value for key is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and the ‘all’ operator is used to check if a specific element at an index is equal to the key.

  • This is converted to a list and is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 2021-09-04T11:15:06+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements