+

Python | Remove all values ​​from a list present in another list

Method # 1: Using List Comprehension
List Comprehension can be used to perform a naive method on only one line and therefore provides a simple method to accomplish this specific task.

# Python 3 demo code
# remove items from another list
# using comprehension list

 
# init list

test_list = [ 1 , 3 , 4 , 6 , 7 ]

 
# initialize list removal

remove_list = [ 3 , 6 ]

 
# print of the original list

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

 
# print delete list

print ( "The original list is:" +   str (remove_list))

 
# using a list comprehension to complete a task

res = [i for i in test_list if i not in remove_list]

 
# print result

print ( "The list after performing remove operation is:" + str (res))

Output:

 The original list is: [1, 3, 4, 6, 7] The original list is: [3, 6 ] The list after performing remove operation is: [1, 4, 7] 

Method # 2: Using filter () + lambda
The filter function can be used in conjunction with a lambda expression to accomplish this task and create a new filtered list of all items that are not in the remove item list.

# Python 3 demo code
# remove items from another list
# using a filter ( ) + lambda

 
# initializing list

test_list = [ 1 , 3 , 4 , 6 , 7 ]

 
# initialize list removal

remove_list = [ 3 , 6 ]

 
# print of the original list

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

 < br /> # print delete list

print ( "The original list is:" + str (remove_list))

 
# using filter () + lambda to execute the task

res = filter ( lambda i: i not in remove_list, test_list)

  
# print result

print ( "The list after performing remove operation is:" + str (res))

Output:

 The original list is: [1, 3 , 4, 6, 7] The original list is: [3, 6] The list after performing remove operation is: [1, 4, 7] 

Method # 3: Using remove()
remove () can also perform this task, but only if the exception is not related to processing a specific element. You can iterate through all the elements of the delete list and remove those elements from the original list.

# Python 3 demo code
# remove items present in another list
# using remove ()

 
# initializing list

test_list = [ 1 , 3 , 4 , 6 , 7 ]

 
# init remove list removal

remove_list = [ 3 , 6 ]

 
# print original list

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

 
# print delete list

print ( "The original list is:" + str (remove_list))

  
# using remove () to complete the task
# exceptions handled.

for i in remove_list:

try :

test_list.remove (i)

except ValueError:

pass

 
# print result

print ( "The list after performing remove operation is:" + str (test_list))

Output:

 The original list is: [1, 3, 4, 6, 7] The original list is: [3, 6] The list after performing remove operation is: [1, 4, 7 ] 
Get Solution for free from DataCamp guru