A quick way to remove items from a list by index in Python

I have a list of characters and a list of indices

myList = ['a','b','c','d']
toRemove = [0,2]

and I would like to get it in one operation

myList = ['b','d']

I could do it, but is there a way to do it faster?

toRemove.reverse()
for i in toRemove:
    myList.pop(i)
+5
source share
5 answers

If you want, you can use numpy.

import numpy as np

myList = ['a','b','c','d']
toRemove = [0,2]

new_list = np.delete(myList, toRemove)

Result:

>>> new_list
array(['b', 'd'], 
      dtype='|S1')

Please note that new_listis numpy array.

+4
source

Short answer

>>> myList = ['a','b','c','d']
>>> toRemove = [0,2]
>>> 
>>> [v for i, v in enumerate(myList) if i not in toRemove]
['b', 'd']
>>> 
+5
source

, , , set , .

>>> myList = ['a','b','c','d']
>>> toRemove = set([0,2])
>>> [x for i,x in enumerate(myList) if i not in toRemove]
['b', 'd']

Checking each element in myList for each inRemove element is O (n * m) (where n is the length of myList and m is the length of toRemove). If you use set, the membership check is O (1), so the whole procedure becomes O (n). Keep in mind, however, the difference in speed will not be noticeable if toRemove is really large (say, more than a thousand).

+5
source

Single line:

>>>[myList[x] for x in range(len(myList)) if not x in [0,2]]
['b', 'd']
+1
source

You can write a function to do this for you.

def removethese(list, *args):
    for arg in args:
        del list[arg]

Then do

mylist = ['a', 'b', 'c', 'd', 'e']
removethese(mylist, 0, 1, 4)

mylist is now ['c', 'd']

0
source

All Articles