- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python â€“ Filter Sorted Rows
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 −
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)
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]]
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.
Kickstart Your Career
Get certified by completing the courseGet Started