I have a list of characters and list of indexes
myList = ['a','b','c','d']
toRemove = [0,2]
and I'd like to get this in one operation
myList = ['b','d']
I could do this but is there is a way to do it faster?
toRemove.reverse()
for i in toRemove:
myList.pop(i)
Concise answer
>>> myList = ['a','b','c','d']
>>> toRemove = [0,2]
>>>
>>> [v for i, v in enumerate(myList) if i not in toRemove]
['b', 'd']
>>>
You could use a list comprehension as other answers have suggested, but to make it truly faster I would suggest using a set
for the set of indices you want removed.
>>> myList = ['a','b','c','d']
>>> toRemove = set([0,2])
>>> [x for i,x in enumerate(myList) if i not in toRemove]
['b', 'd']
Checking every element in myList against every element in toRemove is O(n*m) (where n is the length of myList and m is the length of toRemove). If you use a set
, checking for membership is O(1), so the whole procedure becomes O(n). Keep in mind though, the difference in speed will not be noticeable unless toRemove is really big (say more than a thousand).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With