Python – Filter Sorted Rows

When it is required to filter sorted rows, a list comprehension and the sorted() method are used. This technique helps identify sublists that are already sorted in either ascending or descending order.

What are Sorted Rows?

A sorted row is a sublist where elements are arranged in either ascending order (1, 4, 15, 99) or descending order (99, 15, 4, 1). We can filter these using list comprehension ?

Example

my_list = [[99, 6, 75, 10], [1, 75, 2, 4, 99], [75, 15, 99, 2], [1, 4, 15, 99]]

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

my_result = [sub for sub in my_list if sub == list(sorted(sub)) or sub == list(sorted(sub, reverse=True))]

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

Output

The list is :
[[99, 6, 75, 10], [1, 75, 2, 4, 99], [75, 15, 99, 2], [1, 4, 15, 99]]
The resultant list is :
[[1, 4, 15, 99]]

How It Works

The list comprehension checks each sublist against two conditions:

  • sub == list(sorted(sub)) − checks if the sublist is sorted in ascending order
  • sub == list(sorted(sub, reverse=True)) − checks if the sublist is sorted in descending order

Alternative Approach Using Functions

You can also create a separate function to check if a list is sorted ?

def is_sorted(lst):
    return lst == sorted(lst) or lst == sorted(lst, reverse=True)

my_list = [[99, 6, 75, 10], [5, 4, 3, 2, 1], [1, 75, 2, 4, 99], [1, 4, 15, 99]]

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

filtered_list = [sub for sub in my_list if is_sorted(sub)]

print("The filtered sorted rows are :")
print(filtered_list)
The list is :
[[99, 6, 75, 10], [5, 4, 3, 2, 1], [1, 75, 2, 4, 99], [1, 4, 15, 99]]
The filtered sorted rows are :
[[5, 4, 3, 2, 1], [1, 4, 15, 99]]

Conclusion

Use list comprehension with sorted() to filter rows that are already sorted in ascending or descending order. This approach efficiently identifies organized data within nested lists.

Updated on: 2026-03-26T00:54:44+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements