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

When working with matrices (lists of lists), you often need to filter rows based on their length. Python provides several approaches to extract rows of a specific length from a matrix.

Using List Comprehension

List comprehension offers a concise way to filter rows by length ?

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

print("The matrix is:")
print(matrix)

target_length = 4

result = [row for row in matrix if len(row) == target_length]

print("Rows with length", target_length, ":")
print(result)
The matrix is:
[[22, 4, 63, 7], [24, 4, 85], [95], [2, 55, 4, 7, 91], [5, 31, 1]]
Rows with length 4 :
[[22, 4, 63, 7]]

Using filter() Function

The filter() function provides an alternative approach ?

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

target_length = 3

result = list(filter(lambda row: len(row) == target_length, matrix))

print("Rows with length", target_length, ":")
print(result)
Rows with length 3 :
[[24, 4, 85], [5, 31, 1]]

Using a Regular Loop

A traditional for loop approach for better readability ?

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

target_length = 5
result = []

for row in matrix:
    if len(row) == target_length:
        result.append(row)

print("Rows with length", target_length, ":")
print(result)
Rows with length 5 :
[[2, 55, 4, 7, 91]]

Finding Multiple Lengths

You can also filter rows that match multiple length criteria ?

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

target_lengths = [3, 4]

result = [row for row in matrix if len(row) in target_lengths]

print("Rows with lengths", target_lengths, ":")
print(result)
Rows with lengths [3, 4] :
[[22, 4, 63, 7], [24, 4, 85], [5, 31, 1]]

Comparison

Method Readability Performance Best For
List Comprehension High Fast Simple filtering
filter() Function Medium Fast Functional programming style
Regular Loop High Slightly slower Complex logic or debugging

Conclusion

List comprehension is the most Pythonic way to filter matrix rows by length. Use filter() for functional programming approaches or regular loops when you need more complex filtering logic.

Updated on: 2026-03-26T01:49:15+05:30

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements