0

I have an index of list elements that I want to delete. How can I do that ?

For example, if my original list is a=[1,2,3,4,5,6] and my index list is [2,3]. I want the elements 3,4 to be removed

pikachuchameleon
  • 665
  • 3
  • 10
  • 27

2 Answers2

1

Since you want to delete the indices, you can do the following two methods:

In place:

for index in sorted(indices, reversed=True):
    del a[index]

out of place:

new_a = [el for index, el in enumerate(a) if index not in indices]

The reason why we sort for the in-place version is because deleting from the back doesn't modify the referenced elements in the front (note that this breaks with negative indexing).

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60
0
a=[1,2,3,4,5,6]
a = a[:2] + a[4:]
print(a)
[1, 2, 5, 6]
LetzerWille
  • 5,355
  • 4
  • 23
  • 26