0

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?

4
  • 1
    Remove the indices in reverse order? Commented Mar 24, 2021 at 4:18
  • 2
    Start from the largest one, i.e. remove 4th element first, then 3rd, then 0th. Commented Mar 24, 2021 at 4:18
  • first, get all the values in a different list and then remove it Commented Mar 24, 2021 at 4:18
  • Do something like new list = [j for i, j in enumerate(a_list) if i not in [0, 7, 9]] .... another solution is instead of removing items, replace them with a temporary number or character eg 0... and then add an extra line... list(filter((0).__ne__, a_list)) or list(filter(lambda a: a != 2, a_list)) Commented Mar 24, 2021 at 4:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A possible optimization is to convert outliers to a set
Could be better to use a set but I assumed outliers contains distinct element
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.