Python program to remove row with custom list element


When it is required to remove row with custom list element, a list comprehension and the ‘any’ operator are used.

Example

Below is a demonstration of the same

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

  • A list of integers is defined and is displayed on the console.
  • A list of integers is defined as ‘check_list’ and is displayed on the console.
  • A list comprehension is used to iterate over the elements and the ‘any’ operator is used.
  • Here, it is checked to see if an element in the row matches with the elements provided in the ‘check_list’
  • If yes, the row is stored in a list.
  • This is assigned to a variable.
  • This is displayed as output on the console.

Updated on: 16-Sep-2021

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements