When it is required to filter sorted rows, a list comprehension and the ‘sorted’ and ‘list’ methods are used.
Below is a demonstration of the same −
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]]
Explanation
A list of list is defined and is displayed on the console.
A list comprehension is used to iterate over the elements and check if the sorted elements is equal to the original list or reversed sorted list
If yes, it is converted to a list, and assigned to a variable.
This is displayed as output on the console.