remove multiple items from list in python

How to Remove Multiple Items from List in Python

Sometimes you may need to delete multiple items from list in Python. In this article, we will look at different ways to remove multiple items from list in Python.


How to Remove Multiple Items from List in Python

Here are the different ways to remove multiple items from list in Python. Let us say you have the following list.

>>> a = [1, 2, 3, 4, 5, 6]


1. Using condition

Sometimes you may need to delete items based on a condition such as remove all even elements from list.. Here is an example to remove even numbered elements from list. We use modulus operator (%) to determine if an item is even or odd.

>>> a=[1,2,3,4,5,6]
>>> for i in a:
	if i%2==0:
		a.remove(i)		
>>> a
[1, 3, 5]

In this case, we loop through the elements and remove them one by one, if they are even.

You can do the same thing using list comprehension, as shown below.

>>> a=[i for i in a if i%2!=0]
>>> a
[1, 3, 5]


2. Remove adjacent elements

If you want to remove multiple adjacent elements you can do so using the del command as shown below. Let us say you want to delete elements with indices 1-3 in a list.

>>> a=[1,2,3,4,5,6]
>>> del a[1:4]
>>> a
>>> [1,5,6]


3. Using another list or tuple

Sometimes you may want to remove items that are present in one list, from another list. Let us say you want to remove elements present in list b, from list a. You can easily do this using list comprehensions as shown below.

>>> a=[1,2,3,4,5,6]
>>> b=[2,3]
>>> a = [ele for ele in a if ele not in b]
>>> a
[1, 4, 5, 6]


4. Using indices

If you know the indices of elements to be deleted, you can use a for loop and del command to remove those items. Let us say you have a list c with indices of elements to be deleted. Here is how to delete those elements from our list a.

>>> a=[1,2,3,4,5,6]
>>> c=[3,4]
>>> for i in sorted(c,reverse=True):
	del a[i]
>>> a
[1, 2, 3, 6]

In the above code we loop through the list of indices c in reverse order and delete those items one by one from our list a. We have to delete the element in reverse order because if you delete an element with smallest index, it will reduce the indices of all other subsequent elements, and we will end up deleting wrong elements. So we start the highest index and move to the smallest one.

In this article, we have seen 4 different ways to delete list items. Use the one that fits your requirements.

Also read :

How to Flatten List of Dictionaries in Python
How to Flatten List of Tuples in Python
How to Find & Remove Broken Symlinks
How to Remove Duplicates from List
How to Get Key from Value in Python

Leave a Reply

Your email address will not be published. Required fields are marked *