Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Filter rows with required elements
When it is required to filter rows with required elements, a list comprehension and the all() operator can be used to check if all elements in each row are present in a reference list.
Example
The following example demonstrates how to filter rows where all elements are present in a check list ?
my_list = [[261, 49, 61], [27, 49, 3, 261], [261, 49, 85], [1, 1, 9]]
print("The list is :")
print(my_list)
check_list = [49, 61, 261, 85]
my_result = [row for row in my_list if all(element in check_list for element in row)]
print("The result is :")
print(my_result)
The list is : [[261, 49, 61], [27, 49, 3, 261], [261, 49, 85], [1, 1, 9]] The result is : [[261, 49, 61], [261, 49, 85]]
How It Works
The solution uses a list comprehension combined with the all() function:
A list of lists (rows) is defined and displayed on the console.
A reference list (
check_list) containing valid elements is defined.The list comprehension iterates over each row in the original list.
The
all()operator checks if every element in the current row exists incheck_list.Only rows where all elements pass this condition are included in the result.
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
my_list = [[261, 49, 61], [27, 49, 3, 261], [261, 49, 85], [1, 1, 9]]
check_list = [49, 61, 261, 85]
my_result = list(filter(lambda row: all(element in check_list for element in row), my_list))
print("The result is :")
print(my_result)
The result is : [[261, 49, 61], [261, 49, 85]]
Conclusion
Use list comprehension with all() to filter rows where every element exists in a reference list. This approach is efficient and readable for checking multiple conditions across nested data structures.
