# Python 3 code to demonstrate
# to remove elements present in other list
# using filter() lambda
# initializing list
list1 = [1, 3, 4, 6, 7]
# initializing remove list
list2 = [3, 6]
# printing original list
print("The original list is : " str(list1))
# printing remove list
print("The original list is : " str(list2))
# using filter() lambda to perform task
res = filter(lambda i: i not in list1, list2)
# printing 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 : <filter object at 0x000001D5A0952FA0>
Expected 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]
What is the problem here? Why am I getting that error. I really can't wrap my head around this issue. I found this in website called geeksforgeeks and tried to run it.
https://www.geeksforgeeks.org/python-remove-all-values-from-a-list-present-in-other-list/
CodePudding user response:
the two lists are in the wrong places and to display the result you can transform the filter object into a list
res = list(filter(lambda i: i not in list2, list1))
print("The list after performing remove operation is : " str(res))
OUTPUTS: The list after performing remove operation is : [1, 4, 7]
CodePudding user response:
you need to change your filter functions argument. Your code should like this
list1 = [1, 3, 4, 6, 7]
# initializing remove list
list2 = [3, 6]
# printing original list
print("The original list is : " str(list1))
# printing remove list
print("The original list is : " str(list2))
# using filter() lambda to perform task
res = list(filter(lambda i: i not in list2, list1))
print(list1)
print(list2)
print(res)
output of this code will be like this
The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
[1, 3, 4, 6, 7]
[3, 6]
[1, 4, 7]