Deleting multiple elements of a list
Posted March 25, 2014 at 06:40 PM | categories: python | tags:
Today someone asked about deleting multiple elements from a list (actually it was about deleting multiple atoms from an ase.Atoms object, but some principles here apply. I will address that actual question later.).
Deleting multiple items from a list is not directly possible in one command in Python. There are a few approaches to accomplishing something like it. Which one is best depends on your objective.
One problem is when you delete an item, the indices of every item after it also changes. One strategy then is to delete the elements in descending order, i.e. delete the largest indices first. That way, you do not change the indices of the smaller indices, so you can still delete them. We can sort them in reverse order like this:
a = [1, 2, 5, 6, 7] ind2remove = [1, 3] for i in sorted(ind2remove, reverse=True): del a[i] print a
[1, 5, 7]
An alternative approach is to make a new list that only has the elements you want using list comprehension. For example:
a = [1, 2, 5, 6, 7] ind2remove = [1, 3] a = [x for i,x in enumerate(a) if i not in ind2remove] print a
[1, 5, 7]
With numpy arrays you can delete multiple elements like this:
import numpy as np a = np.array([1, 2, 5, 6, 7]) ind2remove = [1, 3] print np.delete(a, ind2remove) print a
[1 5 7] [1 2 5 6 7]
The delete command makes a new object; the original list is unchanged. Numpy arrays are technically immutable, so the only way to do this is to make a copy. Another way is to use a boolean mask that only selects the indices where the mask is True, and not where they are False.
import numpy as np a = np.array([1, 2, 5, 6, 7]) ind2remove = [1, 3] mask = np.ones(len(a), dtype=bool) mask[ind2remove] = False print a[mask] print a
[1 5 7] [1 2 5 6 7]
There might be other ways to do this too. These examples are nearly indistinguishable for small lists. For very large lists (I guess 1000's of elements), you may find one method more efficient than the others.
Copyright (C) 2014 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.5h