Python Program that prints the rows of a given length from a matrix

PythonServer Side ProgrammingProgramming

When it is required to print the row of a specific length from a matrix, list comprehension is used.

Example

Below is a demonstration of the same

my_list = [[22, 4, 63, 7], [24, 4, 85], [95], [2, 55, 4, 7, 91], [5, 31, 1]]

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

my_key = 4

my_result = [sub for sub in my_list if len(sub) == my_key]

print("The resultant list is :")
print(my_result)

Output

The list is :
[[22, 4, 63, 7], [24, 4, 85], [95], [2, 55, 4, 7, 91], [5, 31, 1]]
The resultant list is :
[[22, 4, 63, 7]]

Explanation

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

  • A key value is defined.

  • The list comprehension is used to iterate through the list, and the length of every element is checked to be equal to the key.

  • This is assigned to a variable.

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

raja
Published on 14-Sep-2021 10:39:05
Advertisements