Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to remove elements from list by index in Python

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)
like image 938
Youcha Avatar asked Jun 07 '12 22:06

Youcha


2 Answers

Concise answer

>>> myList = ['a','b','c','d']
>>> toRemove = [0,2]
>>> 
>>> [v for i, v in enumerate(myList) if i not in toRemove]
['b', 'd']
>>> 
like image 139
Nick Craig-Wood Avatar answered Oct 21 '22 00:10

Nick Craig-Wood


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).

like image 20
MAK Avatar answered Oct 21 '22 00:10

MAK