1

I am writing a piece of code that goes through a list and if the item meets a certain criteria, it is added to a different list and deleted from the current list. For example:

for item in range(len(myList)):
    if (Insert Condition):
        newList.append(item)
        del(myList[item])

When I do this, I receive a 'list assignment index out of range' error.

Is this occurring because the range that the loop must go through is now longer than the list itself?

  • 3
    don't delete stuff from a list you are iterating over, just don't, it's not worth the headaches – SuperStew Oct 30 '19 at 21:11
  • It looks like you want to move some items from `myList` to `newList`. You would be better off making two new lists. – quamrana Oct 30 '19 at 21:12

2 Answers2

1

Is this occurring because the range that the loop must go through is now longer than the list itself?

Yes. Your loop only gets the length of the list once, when the loop starts. If the list initially has 10 elements, you'll loop from 0 to 9. If you delete an element from the list, the last index will be lower than 9, but the loop will still go all the way to 9 and you'll try to access nonexistent list indexes.

You can solve the problem by iterating in reverse.

for item in range(len(myList), 0, -1):
    if (insert condition):
        newList.append(myList[item])
        del(myList[item])

This works because removing an element doesn't affect the elements with lower indexes.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can make two new lists like this:

newList = [item for item in myList if (Insert Condition)]
newMyList = [item for item in myList if not (Insert Condition)]

If necessary, you can conclude with:

myList = newMyList

which will drop the original list.

quamrana
  • 37,849
  • 12
  • 53
  • 71