- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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 −
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.
Advertisements