In this article, we are going to learn logic about how to remove elements from a list present in another list in Python. This will give us two lists with unique elements. We can use the same logic to remove elements from the list python. Also if you need programs in the to python list to remove multiple elements, that will also work. We are going to do this in multiple ways. We will use 3 different logic functions to perform this task.
1. Lambda to Remove elements from a list present in another list Python
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
syntax:
filter(function, sequence)
Parameters:
- function: a function that tests if each element of a sequence is true or not.
- sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.
- Returns: returns an iterator that is already filtered.
How does it work?
- Two lists are given.
- In the first method I use the filter and lambda function.
- In the lambda function I iterate the second list and check if the element of second list is present in list 1
then remove it from list one and print updated list1.
list1=[1,2,3,4,5,6,7,8]
list2=[2,4,6]
print("First Method")
list(filter(lambda x:list1.remove(x) if x in list1 else list1,list2))
print(list1)
Output:-
First Method
[1, 3, 5, 7, 8]
2.Remove elements from a list present in another list Python by index/value
- Two lists are given.
- In the second method I also use the filter and lambda function but in that method a new list is created.
- In that method I iterate the list1 and check if the element not in second list then stored in new list and print it.
sprint("second Method")
list1=[1,2,3,4,5,6,7,8]
list2=[2,4,6]
res=list(filter(lambda x: x not in list2,list1))
print(res)
Output:-
second Method
[1, 3, 5, 7, 8]
3. Python program to remove item from list python by value
- Two lists are given.
- In the third method I remove the duplicate element by using loop and lambda function.
- Iterate the list1 and check if element of list1 is present in list 2 then called the lambda function in which there is expression to remove the element from list.
- At last print the updated list1.
#Remove elements from a list present in another list Python
print("Third method")
list1=[1,2,3,4,5,6,7,8]
list2=[2,4,6]
x=lambda x:list1.remove(x)
for i in list1:
if i in list2:
x(i)
print(list1)
Output:-
Third method
[1, 3, 5, 7, 8]