Python - Print rows from the matrix that have same element at a given index

PythonServer Side ProgrammingProgramming

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.

Published on 04-Sep-2021 11:14:37