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])
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])
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]
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?
Edit
The above code runs loop on range(len(urls)-1)
which means if there are 4 elements in list, then it becomes range(0,3) and in turn iterates over 0, 1, 2 only. Hence, the last index is never reached.
So the error will come after popping the second None
. However, the intention seems to traverse the whole list and hence range(len(urls))
would be more appropriate in original code.