You can do Iterating or List Comprehension to remove multiple items from the list in Python. Removing adjacent elements using list slicing is another option.
Python removes multiple items from the list
Simple example code uses in-built functions to remove elements from a list. Numbers that are divisible by 5 should be deleted from the list.
Iterating: iterate over the list and remove them one by one if it is divisible by 5.
li = [10, 3, 12, 15, 5, 8]
for i in list(li):
if i % 5 == 0:
li.remove(i)
print(li)
List Comprehension: this is a shorter syntax for creating a new list based on the values of an existing list.
li = [10, 3, 12, 15, 5, 8]
li = [num for num in li if num % 5 != 0]
print(li)
Output:
If you want user input value then use this code
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
li=[num for num in li if num%5!=0]
print("List after removing elements ",li)
You can use a loop to iterate through the items to be removed and remove them one by one using the remove()
method.
my_list = [1, 2, 3, 4, 5]
items_to_remove = [2, 4]
for item in items_to_remove:
my_list.remove(item)
print(my_list)
Using list slicing
Below Python code remove values from index 1 to 4.
list1 = [11, 5, 17, 18, 23, 50]
# removes elements from index 1 to 4
# i.e. 5, 17, 18, 23 will be deleted
del list1[1:5]
print(*list1)
Do comment if you have any doubts or suggestions on this Python remove topic
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.