1

I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

del_list = [0, 4, 11]

desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]

Here is what I have done

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

for element in index_list:
    del x[element]

print(x)

I get this error. I can figure out that because of deleting elements the list shortens and the index goes out of range. But i am not sure how to do it

Traceback (most recent call last):
IndexError: list assignment index out of range
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
dhruv
  • 13
  • 1
  • 3
  • it is because after deleting 0th and 4th index element total list size is not > 11, that's why it gives `index out of range error`. – Nihal Aug 11 '18 at 07:07
  • Use `x = [e for i, e in enumerate(x) if i not in index_list]`, well known pattern – user3483203 Aug 11 '18 at 07:39

3 Answers3

1

You could also use enumerate:

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]
new_x = []
for index, element in enumerate(x):
    if index not in index_list:
        new_x.append(element)
print(new_x)
Abhi
  • 4,068
  • 1
  • 16
  • 29
0

This question already has an answer here. How to delete elements from a list using a list of indexes?.

BTW this will do for you

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

value_list = []
for element in index_list:
    value_list.append(x[element])

for element in value_list:
    x.remove(element)

print(x)
Navneet
  • 253
  • 3
  • 12
0

You can sort the del_list list in descending order and then use the list.pop() method to delete specified indexes:

for i in sorted(del_list, reverse=True):
    x.pop(i)

so that x would become:

[45, 55, 6, 37, 656, 78, 8, 99, 9]
blhsing
  • 91,368
  • 6
  • 71
  • 106