Remove list of indexes from list in Python

I have a list with dots (centroids), and some of them need to be deleted.

How can I do this without loops? I tried the answer given here , but this error is shown:

list indices must be integers, not list

My listings are as follows:

centroids = [[320, 240], [400, 200], [450, 600]]
index = [0,2]

And I want to delete items in index. The end result will be:

centroids = [[400, 200]]
+4
source share
3 answers

Here is another very interesting way.

 map(centroids.__delitem__, sorted(index, reverse=True))

It will actually remove the items in place.

+3
source

You can use enumeratein understanding the list:

>>> centroids = [[320, 240], [400, 200], [450, 600]]
>>> index = [0,2]
>>> [element for i,element in enumerate(centroids) if i not in index]
[[400, 200]]

, , , , , . , C ( 2 ), python!

set, O (1) .

+8

You can do this in numpy using delete .

eg.

 import numpy as np
 centroids = np.array([[320, 240], [400, 200], [450, 600]])
 index = [0,2]
 np.delete(arr, index, 0)

gives

[[400, 200]]
0
source

All Articles