Python – Filter Rows with Range Elements

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

When it is required to filter rows with range elements, a list comprehension and the ‘all’ operator is used to determine the output.

Below is a demonstration of the same −

Example

Live Demo

my_list = [[3, 2, 4, 5, 10], [32, 12, 4, 51, 10],[12, 53, 11], [2, 3, 31, 5, 8, 7]]

print("The list is :")
print(my_list)

i, j = 2, 5

my_result = [index for index in my_list if all(element in index for element in range(i, j + 1))]

print("The result is :")
print(my_result)

Output

The list is :
[[3, 2, 4, 5, 10], [32, 12, 4, 51, 10], [12, 53, 11], [2, 3, 31, 5, 8, 7]]
The result is :
[[3, 2, 4, 5, 10]]

Explanation

• A list of list is defined and displayed on the console.

• The value for integers ‘i’ and ‘j’ are defined.

• A list comprehension is used to iterate over the list, and check if all the elements belong to the range specified by the two integers previously defined.

• If yes, it is converted to a list.

• This result is assigned to a variable.

• This is the output that is displayed on the console.

Updated on 06-Sep-2021 08:47:47