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
- Initialize the list
- Then we will iterate the list.
- Then we will apply the condition.
- Then we will use the remove() function to remove the element from the list
- 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
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
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
Conclusion
In this article, we will learn to remove multiple elements in a list using different methods in python.