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
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.