Home > Software engineering >  List index out of range when trying to remove instance from list
List index out of range when trying to remove instance from list

Time:12-14

The out of range error shows when I try to remove an instance from a list but doesn't pop up when I just pass the statement?

for x in range(len(urls)-1):
  if urls[x] == None:
    urls.remove(urls[x])

CodePudding user response:

This is because you're removing from the list while starting the loop executing len(url) - 1 times. Total number of iterations will not be adjusted once you start removing from the list; and decreasing the length. Instead, you should use list comprehension for this.

new_list = [x for x in urls if x is not None]

CodePudding user response:

This will happen even if there is a single None in your list.

The last index of the list which was valid before loop, will not be valid after popping a None because the list has shrunk by one.

Subsequent popping of your None element will result in subsequent shrinking of list and subsequent invalidity of 'second, third, fourth... from last' indexes.

Check workarounds here How to remove items from a list while iterating?

  • Related