Skip to content

Python remove multiple items from list

  • by

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:

Python remove multiple items from list

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)

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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.