Remove multiple elements from a list in Python

In this article, we will remove multiple elements from the list in python programming.

Example

Input : [ 1, 2, 3, 4]
Remove : [2, 4]
Output: New_list =  [1, 3]

Method 1: Iterating

In this method, we will remove the elements one by one, which is divisible by 2 using the remove() function.

Explanation

  1. Initialize the list
  2. Then we will iterate the list.
  3. Then we will apply the condition.
  4. Then we will use the remove() function to remove the element from the list
  5. After that, we will print the final updated list.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# initialize the list
list = [1, 2, 3, 4, 5, 6, 7, 8]

# iterate the list
for ele in list:
    if (ele%2==0):
        list.remove(ele)  # use remove() function

# print the list after removing elements
print(list)
   

Output

[1, 3, 5, 7]

Method 2: List Comprehension

List comprehension is a concise way to create a new list by performing operations on elements of an existing list. We can use list comprehension to create a new list by excluding the elements that meet certain conditions. The new list will have all the elements that don't match the conditions.

For example, if we have a list of numbers and we want to remove all even numbers from the list, we can use the following code:

Program

1
2
3
4
5
6
7
8
#initilaize the list 
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# create another list using list comprehension
odd_numbers = [num for num in numbers if num % 2 != 0]

# print the new list
print(odd_numbers)

Output

[1, 3, 5, 7, 9]

Method 2: Using a filter

The filter function is used to filter elements from a list based on a given condition. We can use the filter function to remove elements that meet certain conditions.

For example, if we have a list of numbers and we want to remove all even numbers from the list, we can use the following code:

Program

1
2
3
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers)

Output

[1, 3, 5, 7, 9]

Conclusion

In this article, we will learn to remove multiple elements in a list using different methods in python.
Next Post Previous Post
No Comment
Add Comment
comment url