Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0]
, followed by del somelist[2]
, the second statement will actually delete somelist[3]
.
I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
Probably not the best solution for this problem:
indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]
Almost, only if you delete the entire list. it'll be len(indices) * len(somelist). It also creates a copy, which may or may not be desired
if you're checking for a value in a list, it is. the 'in' operator works on the values of a list, whereas it works on the keys of a dict. If i'm wrong, please point me to the pep/reference
the reason that i've chosen tuple for indices was only simplicity of the record. it would be a perfect job for set() giving O(n)
This is not deleting items from somelist at all, but rather creating a brand new list. If anything is holding a reference to the original list, it will still have all the items in it.
@SilentGhost Not necessary to make an enumeration. How about this:
somelist = [ lst[i] for i in xrange(len(lst)) if i not in set(indices) ]
?