Python – Rows with all List elements

When it is required to find rows that contain all elements from a given list, a flag value, simple iteration and the 'append' method can be used. This is useful for filtering data based on multiple criteria.

Example

Below is a demonstration of finding rows containing all specified elements ?

my_list = [[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]]

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

sub_list = [1, 2]

result = []
for row in my_list:
   flag = True
   
   for element in sub_list:
      if element not in row:
         flag = False
   if flag:
      result.append(row)

print("The resultant list is :")
print(result)

The output of the above code is ?

The list is :
[[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]]
The resultant list is :
[[2, 1, 7], [8, 1, 2]]

Using List Comprehension with all()

A more concise approach using list comprehension and the built-in all() function ?

my_list = [[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]]
sub_list = [1, 2]

result = [row for row in my_list if all(element in row for element in sub_list)]

print("The list is :")
print(my_list)
print("Elements to find :")
print(sub_list)
print("Rows containing all elements :")
print(result)
The list is :
[[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]]
Elements to find :
[1, 2]
Rows containing all elements :
[[8, 6, 3, 2], [2, 1, 7], [8, 1, 2]]

How It Works

The algorithm checks each row in the main list:

  • A flag is initially set to True for each row

  • Each element from the target list is checked against the current row

  • If any element is not found, the flag becomes False

  • Only rows with flag remaining True are added to results

Comparison

Method Readability Performance Best For
Flag-based loop Moderate Good Learning logic flow
List comprehension + all() High Better Concise filtering

Conclusion

Use the flag-based approach for clarity when learning. For production code, prefer list comprehension with all() for cleaner, more readable filtering of rows containing all specified elements.

Updated on: 2026-03-26T01:51:33+05:30

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements