Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program that filters out non-empty rows of a matrix
When working with matrices (lists of lists), you often need to filter out empty rows. Python provides several approaches to remove non-empty rows from a matrix using list comprehension, the filter() function, or loops.
Using List Comprehension
List comprehension with len() provides a clean and readable solution ?
my_matrix = [[21, 52, 4, 74], [], [7, 8, 4, 1], [], [9, 2]]
print("The original matrix is:")
print(my_matrix)
# Filter out empty rows using list comprehension
filtered_matrix = [row for row in my_matrix if len(row) > 0]
print("The matrix after filtering empty rows:")
print(filtered_matrix)
The original matrix is: [[21, 52, 4, 74], [], [7, 8, 4, 1], [], [9, 2]] The matrix after filtering empty rows: [[21, 52, 4, 74], [7, 8, 4, 1], [9, 2]]
Using filter() Function
The filter() function offers an alternative approach ?
my_matrix = [[1, 2, 3], [], [4, 5], [], [6]]
print("Original matrix:")
print(my_matrix)
# Using filter() with len function
filtered_matrix = list(filter(len, my_matrix))
print("Filtered matrix:")
print(filtered_matrix)
Original matrix: [[1, 2, 3], [], [4, 5], [], [6]] Filtered matrix: [[1, 2, 3], [4, 5], [6]]
Using Boolean Check
You can also filter using truthiness of lists ?
my_matrix = [['a', 'b'], [], ['c'], [], ['d', 'e', 'f']]
print("Original matrix:")
print(my_matrix)
# Empty lists are falsy, non-empty lists are truthy
filtered_matrix = [row for row in my_matrix if row]
print("Filtered matrix:")
print(filtered_matrix)
Original matrix: [['a', 'b'], [], ['c'], [], ['d', 'e', 'f']] Filtered matrix: [['a', 'b'], ['c'], ['d', 'e', 'f']]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
List comprehension with len()
|
High | Fast | Most cases |
filter(len, matrix) |
Medium | Fast | Functional programming |
Boolean check if row
|
High | Fastest | Simple filtering |
Conclusion
Use list comprehension with boolean check if row for the most readable and efficient solution. The len() method is explicit but slightly slower, while filter() works well in functional programming contexts.
Advertisements
