Open In App

Remove Multiple Elements from List in Python

Last Updated : 26 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list.

a = [10, 20, 30, 40, 50, 60, 70]

# Elements to remove
remove = [20, 40, 60]

# Remove elements using a simple for loop
res = []

for val in a:
    if val not in remove:
        res.append(val)

print(res)

Output
[10, 30, 50, 70]

Explanation

  • Iterate through each element in the original list a and adding it to result if it’s not in remove list.

Let’s explore other different ways to remove multiple elements from list:

Using List Comprehension

List comprehension is one of the most concise and efficient ways to remove multiple elements from a list.

a = [10, 20, 30, 40, 50, 60, 70]

# Elements to remove
remove = [20, 40, 60]

# Remove elements using list comprehension
a = [x for x in a if x not in remove]

print(a)

Output
[10, 30, 50, 70]

Explanation:

  • Iterate over each element in a and checking if it is not in remove list.
  • Elements not in remove list are included in the new list.

Using remove() in a Loop

remove() method removes the first occurrence of a specified element from the list. To remove multiple elements, we can use a loop to repeatedly call remove().

a = [10, 20, 30, 40, 50, 60, 70]

# Elements to remove
remove = [20, 40, 60]

# Remove elements using remove() in a loop
for val in remove:
    while val in a:
        a.remove(val)

print(a)

Output
[10, 30, 50, 70]

Explanation:

  • We iterate over each element in remove list.
  • The while loop make sure that all occurrences of each element are removed from the list.

Using filter() Function

filter() function can be used to remove elements from a list by providing a filtering condition and typically through a lambda function.

a = [10, 20, 30, 40, 50, 60, 70]

# Elements to remove
remove = {20, 40, 60}

# Remove elements using filter
a = list(filter(lambda x: x not in remove, a))

print(a)

Output
[10, 30, 50, 70]

Explanation:

  • filter() function iterates over the list a and applying the lambda function.
  • If an element is not in remove list then include it in the filtered list.


Next Article

Similar Reads

three90RightbarBannerImg