1

I have the following list in Python:

x = [[1,2],[3,4],[5,'inf'],[6,7],['nan',10]]

I also have the following index list:

idx = [2,4]

I'm trying to remove the elements from the list x corresponding to the index values in idx. For that, I did the following:

for i in idx:
    del x[i]

I however got the following error:

IndexError: list assignment index out of range

How can I solve this issue?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • Either use a list comprehension or iterate in reverse by index and delete. – cs95 Jan 23 '18 at 17:03
  • 2
    Alternative dupe: [How to remove multiple indexes from a list at the same time](https://stackoverflow.com/questions/11303225/how-to-remove-multiple-indexes-from-a-list-at-the-same-time) – Aran-Fey Jan 23 '18 at 17:04

1 Answers1

1

You are deleting the index 2, then the index 4. The index 4 is the last item. As you are deleting the index 2, the last index becomes the index 3. So accessing the index 4 causes an error.

You might want to delete the indexes in reverse to avoid this.

IMCoins
  • 3,149
  • 1
  • 10
  • 25
  • @Willem Van Onsem Dunno if you downvoted, but he was calling the indexes, and not the elements. – IMCoins Jan 23 '18 at 17:15