Python – Filter Rows with Range Elements

When working with nested lists, you may need to filter rows that contain all elements from a specific range. Python provides an elegant solution using list comprehension with the all() function to check if every element in a range exists within each row.

Syntax

filtered_rows = [row for row in nested_list if all(element in row for element in range(start, end + 1))]

Example

Let's filter rows that contain all numbers from 2 to 5 ?

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 = [row for row in my_list if all(element in row for element in range(i, j + 1))]

print("The result is:")
print(my_result)
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]]

How It Works

The solution uses these key components:

  • List comprehension − iterates through each row in the nested list

  • range(i, j + 1) − generates numbers from 2 to 5 (inclusive)

  • all() function − returns True only if every element in the range exists in the current row

  • element in row − checks membership for each range element

Step-by-Step Breakdown

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

# Range to check (2, 3, 4, 5)
i, j = 2, 5
target_range = list(range(i, j + 1))
print("Target range:", target_range)

# Check each row manually
for idx, row in enumerate(my_list):
    contains_all = all(element in row for element in target_range)
    print(f"Row {idx}: {row} - Contains all range elements: {contains_all}")
Target range: [2, 3, 4, 5]
Row 0: [3, 2, 4, 5, 10] - Contains all range elements: True
Row 1: [32, 12, 4, 51, 10] - Contains all range elements: False
Row 2: [12, 53, 11] - Contains all range elements: False
Row 3: [2, 3, 31, 5, 8, 7] - Contains all range elements: False

Alternative Approach Using Sets

For better performance with larger datasets, you can use set operations ?

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

i, j = 2, 5
target_set = set(range(i, j + 1))

# Using set.issubset() for faster membership testing
my_result = [row for row in my_list if target_set.issubset(set(row))]

print("Filtered rows:", my_result)
Filtered rows: [[3, 2, 4, 5, 10]]

Conclusion

Use list comprehension with all() to filter rows containing all elements from a specific range. For larger datasets, consider using set operations with issubset() for improved performance.

Updated on: 2026-03-26T01:06:21+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements