Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to remove row with custom list element
When working with lists of lists (2D arrays) in Python, there are scenarios where you need to remove entire rows that contain specific elements. This operation is commonly performed using list comprehension combined with the any() function to efficiently filter out unwanted rows.
The any() function returns True if at least one element in an iterable is True. When combined with list comprehension, it provides a concise way to check if any element from a custom list exists in each row.
How It Works
The filtering process involves:
List comprehension − Iterates through each row in the main list
any() function − Checks if any element from the custom list exists in the current row
Negation (not) − Keeps only rows that do NOT contain any elements from the custom list
Example
Below is a demonstration of removing rows that contain elements from a custom list:
my_list = [[14, 3, 11], [66, 27, 8], [31, 12, 21], [11, 16, 26]]
print("The list is :")
print(my_list)
check_list = [3, 10, 19, 29, 20, 15]
print("The check list is :")
print(check_list)
my_result = [row for row in my_list if not any(element in row for element in check_list)]
print("The result is :")
print(my_result)
Output
The list is : [[14, 3, 11], [66, 27, 8], [31, 12, 21], [11, 16, 26]] The check list is : [3, 10, 19, 29, 20, 15] The result is : [[66, 27, 8], [31, 12, 21], [11, 16, 26]]
Explanation
Original list − Contains four rows with integer elements
Check list − Contains elements to be filtered out: [3, 10, 19, 29, 20, 15]
Filtering logic − The list comprehension checks each row using
any(element in row for element in check_list)Result − Only the first row [14, 3, 11] is removed because it contains element 3 from the check list
Alternative Approaches
You can also use other methods for the same filtering operation:
# Using filter() function
my_result = list(filter(lambda row: not any(element in row for element in check_list), my_list))
# Using nested loops (less efficient)
my_result = []
for row in my_list:
should_keep = True
for element in check_list:
if element in row:
should_keep = False
break
if should_keep:
my_result.append(row)
Conclusion
List comprehension with the any() function provides an efficient and readable way to remove rows containing specific elements from a 2D list. This approach is both concise and performant for filtering operations on nested data structures.
