
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
- Related Questions & Answers
- Filter the rows – Python Pandas
- Python – Filter rows with required elements
- Python – Filter Rows with Range Elements
- Python – Filter rows without Space Strings
- Python – Filter immutable rows representing Dictionary Keys from Matrix
- Python – Filter rows with Elements as Multiple of K
- Python – Filter rows with only Alphabets from List of Lists
- Python – Extract Sorted Strings
- Python – Filter Tuples with Integers
- Python – Filter unique valued tuples
- Python – Filter consecutive elements Tuples
- Python – Filter Similar Case Strings
- Python – Extract Paired Rows
- Python – Filter Strings within ASCII range
- Python – Filter dictionaries with ordered values
Advertisements