Python | Remove all occurrences in a nested list

Python Methods and Functions

Method # 1: Using List Comprehension

List Comprehension can be used as a shorter method than the recommended longer method in a regular loop to accomplish this task, in which we just check for a match and restore the list without the target list element.

# Python3 demo code
# Remove all occurrences in the nested list
# use comprehension list

  
# initializing list

test_list = [[ 4 , 5 ], [ 1 < / code> , 2 , 3 ], [ 4 , 5 ], [ 8 , 9 ], [ 10 , 11 ]]

  
# initialize the list to delete

del_list = [ 4 , 5 ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# print the delete list

print ( " The list to be deleted is: " + str ( del_list))

 
# using comprehension list
# Remove all occurrences in the nested list

res = [i for i in test_list if i! = del_list]

 
# print result

print ( "The list after removal of list element:" + str (res))

Output:

 The original list: [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]] The list to be deleted is: [4, 5] The list after removal of list element: [[1, 2, 3], [8, 9], [10, 11]] 

Method # 2: Using filter () + partial () + operator.ne

The task can also be accomplished using the above functions. The filter function filters and returns a partial list by the partial function, and the equals condition is imposed using the operator.ne method.

# Python3 demo code
# Remove all occurrences in the nested list
# using filter () + partial () + operator.ne

from functools import partial

from operator import ne

 
# initializing list

test_list = [[  4 , 5 ], [ 1 , 2 , 3 ], [ 4 , 5 ], [ 8 , 9 ], [ 10 , 11 ]]

 
# initialize the list to be deleted

del_list = [ 4 , 5 ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# print the delete list

print ( " The list to be deleted is: " + str ( del_list))

 
# using filter () + partial () + operator .ne
# Remove all occurrences in the nested list

res = list  ( filter (partial (ne, del_list), test_list))

 
# print result

print ( "The list after removal of list element:" + str (res))

Output:

 The original list: [[4, 5], [1, 2, 3], [4, 5], [8, 9] , [10, 11]] The list to be deleted is: [4, 5] The list after removal of list element: [[1, 2, 3], [8, 9], [10, 11]]