Python Program that filters out non-empty rows of a matrix


When it is required to filter out non-empty rows from a matrix, a simple list comprehension along with the ‘len’ method can be used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [[21, 52, 4, 74], [], [7, 8, 4, 1], [], []]

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

my_result = [row for row in my_list if len(row) > 0]

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

Output

The list is :
[[21, 52, 4, 74], [], [7, 8, 4, 1], [], []]
The resultant list is :
[[21, 52, 4, 74], [7, 8, 4, 1]]

Explanation

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

  • The list is iterated over using list comprehension.

  • It checks if the length of an element is greater than 0 or not.

  • If yes, it is stored in the list.

  • Otherwise, it is ignored.

  • This is assigned to a variable.

  • This variable is displayed as output on the console.

Updated on: 04-Sep-2021

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements