Reputation: 27
So I have a list
a_list = [0,3,4,7,9,11,15]
and a list of outliers
outliers = [0,3,4]
The outliers is the list of indexes that need to be removed from a_list
So in this case, remove the elements in index 0, 3, 4 from a_list. Result should be:
remove these = [0,7,9]
a_list = [0,3,4,11,15]
If I use the del method, the index will change so once I remove 0th index, I will still remove the 3rd index but instead remove 9 and 4th index will remove 15.
How can I remove items from a_list with the indexes specified in a separate list?
Upvotes: 0
Views: 223
Reputation: 3121
Compare index to outliers
list. If the index
is matching to outliers
then skip it.
print([x for i, x in enumerate(a_list) if i not in outliers])
Better to use set(outliers)
if outliers contain the duplicate elements.
Upvotes: 2
Reputation: 41
Here is a real quick implementation based on what the others were commenting about.
a_list = [0,3,4,7,9,11,15]
outliers = [0,3,4]
outliers.reverse()
for i in outliers:
del a_list[i]
print(a_list)
Simply call outliers.reverse()
before iterating and delete as normal.
Upvotes: -1