Remove Multiple Elements from Python List

There are two ways to remove multiple elements from a list: using list comprehension or a loop.

  1. By using list comprehensions:
my_list = [1, 2, 3, 4, 5]
elements_to_remove = [2, 4]

new_list = [x for x in my_list if x not in elements_to_remove]

print(new_list)
  1. Use a loop:
my_list = [1, 2, 3, 4, 5]
elements_to_remove = [2, 4]

new_list = []
for x in my_list:
    if x not in elements_to_remove:
        new_list.append(x)

print(new_list)

Multiple elements in the list can be deleted using any method.

bannerAds