-1

I'm trying to delete multiple elements from a list. The elements are having their indexes evaluated dynamically, and stored in a list called "dstry". It may look something like this:

arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]

However, if I do...

for i in dstry:
    del arr[i]

The list begins to shrink, and dstry's target elements are no longer where they should be. Logically, how can I get around this? It'd be nice if the del could resolve all at once and delay the collapse of the array. Should I instead replace the elements with a flag value and then del them wherever they appear later so that index is not a factor?

Thanks

KuboMD
  • 684
  • 5
  • 16
  • What is `arr.del`? lists have no `del` method. Do you mean `del arr[i]` ? – DeepSpace Aug 27 '18 at 14:01
  • use arr.remove() instead of del() – Hcetipe Aug 27 '18 at 14:02
  • Use comprehension: `[a for i, a in enumerate(arr) if i not in dstry]`. – zipa Aug 27 '18 at 14:07
  • Reverse `destry` while you loop over it, that way the indices remain faithful: `for i in reversed(dstry): del arr[i]`. That being said, doing it like this is computationally inefficient. The answer in the linked duplicated has a number of superior methods. – Arne Aug 27 '18 at 14:08

1 Answers1

1

A bit creative solution, but this should fix the problem with the index you had.

arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]

x=len(arr)

for i in dstry:
    del arr[-x+i]

print(arr)
Stef van der Zon
  • 633
  • 4
  • 13
  • Thanks for the response. However, remove doesn't serve the proper purpose here as remove is based on the value in the list rather than the index. – KuboMD Aug 27 '18 at 14:05
  • Your current solution only works if `dstry` is sorted from small to large. Just reverse the list, then you don't have to adapt the indices. – Arne Aug 27 '18 at 14:10
  • Changed it to what you said. – Stef van der Zon Aug 27 '18 at 14:18