- 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 rows with required elements
When it is required to filter rows with required elements, a list comprehension and the ‘all’ operator is used.
Below is a demonstration of the same −
Example
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 = [index for index in my_list if all(element in check_list for element in index)] print("The result is :") print(my_result)
Output
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]]
Explanation
A list is defined and displayed on the console.
Another list of integers is defined.
A list comprehension is used to iterate over the list, and the ‘all’ operator is used to see if all the values of the integer list are present in the original list.
If so, it is added to a list, and is assigned to a variable.
This is the output that is displayed on the console.
Advertisements