How to Remove Elements from a List if Present in Another List in Python?

Estimated read time 2 min read

To remove elements from a list if they are present in another list in Python, you can use a list comprehension or the filter() function. Here’s an example using a list comprehension:

list1 = [1, 2, 3, 4, 5, 6]
list2 = [2, 4, 6]

# Remove elements in list1 if they are present in list2
new_list = [x for x in list1 if x not in list2]

print(new_list)  # Output: [1, 3, 5]

In this code, we have two lists (list1 and list2). We want to remove the elements in list1 that are present in list2.

To achieve this, we create a new list (new_list) using a list comprehension that iterates over list1 and includes only the elements that are not present in list2.

Alternatively, you can use the filter() function to achieve the same result. Here’s an example using filter():

list1 = [1, 2, 3, 4, 5, 6]
list2 = [2, 4, 6]

# Remove elements in list1 if they are present in list2 using filter()
new_list = list(filter(lambda x: x not in list2, list1))

print(new_list)  # Output: [1, 3, 5]

In this code, we use the filter() function to remove the elements in list1 that are present in list2. The filter() function takes two arguments: a function that returns a Boolean value, and the iterable to be filtered. In this example, we pass a lambda function that checks if an element is not in list2, and the original list (list1). Finally, we convert the filtered result to a list using the list() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply