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

 Live Demo

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.

Updated on: 2021-09-06T08:07:14+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements