Given a list of numbers, write a Python program to remove multiple elements from a list based on the given condition.
Input: [12, 15, 3, 10] Output: Remove = [12, 3], New_List = [15, 10] Input: [11, 5, 17, 18, 23, 50] Output: Remove = [1:5], New_list = [11, 50]
Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values. Let’s see different examples based on different scenario.
Example #1: Let’s say we want to delete each element in the list which is divisible by 2 or all the even numbers.
New list after removing all even numbers: [11, 5, 17, 23]
Example #2: Using list comprehension
Removing all even elements in a list is as good as only including all the elements which are not even( i.e. odd elements).
11 5 17 23
Example #3: Remove adjacent elements using list slicing
Below Python code remove values from index 1 to 4.
Example #4: Using list comprehension
Let’s say the elements to be deleted is known, instead of the indexes of those elements. In this case, we can directly eliminate those elements without caring about indexes which we will see in next example.
New list after removing unwanted numbers: [17, 18, 23, 50]
Example #5: When index of elements is known.
Though indexes of elements in known, deleting the elements randomly will change the values of indexes. Hence, it is always recommended to delete the largest indices first. Using this strategy, index of smaller values will not be changed. We can sort the list in reverse order and delete the elements of list in descending order.
5 17 50
- Python | Remove last K elements of list
- Python | Remove unordered duplicate elements from a list
- Python | Remove elements of list that are repeated less than k times
- Python | Remove trailing empty elements from given list
- Python | Remove all values from a list present in other list
- Python | Add similar value multiple times in list
- Python | Assign multiple variables with list values
- Python | Convert a list of multiple integers into a single integer
- Python list remove()
- Python | Remove None values from list
- Python | Remove Duplicates from a List
- Python | Ways to remove duplicates from list
- Python | Ways to remove particular list element
- Python | Remove all strings from a list of tuples
- Python | Remove and print every third from list until it becomes empty
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.