(Python) List index out of range - iteration [dupl

2019-02-15 12:16发布

问题:

This question already has an answer here:

  • python : list index out of range error 8 answers
  • How to remove items from a list while iterating? 23 answers
for i in range(len(lst)):    
   if lst[i][0]==1 or lst[i][1]==1:
        lst.remove(lst[i])
return lst

This gives "IndexError: list index out of range" Why is this happening?

回答1:

You're modifying the list you're iterating over. If you do that, the size of the list shrinks, so eventually lst[i] will point beyond the list's boundaries.

>>> lst = [1,2,3]
>>> lst[2]
3
>>> lst.remove(1)
>>> lst[1]
3
>>> lst[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

It's safer to construct a new list:

return [item for item in lst if item[0]!=1 and item[1]!=1]


回答2:

You shouldn't remove items from the list as you iterate over it; that changes the indices of all subsequent items, hence the IndexError. You could try a simple list comprehension:

lst = [item for item in lst if (item[0] != 1 and item[1] != 1)]


回答3:

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [12, 32, 50, 71], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.



回答4:

The problem is that you remove items in the list which reduces its size. What you have to do is make an array with the indexes you want to remove and remove them backwards.

Another way would be to create a temporary list that you would add the elements you don't want to delete and then overwrite your initial list with the list containing all the elements you want to keep.



回答5:

By process of deduction I have concluded that your lst looks something like this:

lst = [ ...[val1, val2], [val1, val2], [val1, val2]... ]

I think what happened here is you confused your 'for i in range', with a 'for i in' (I have done this many times also.)

The line where your error is occurring is:
lst.remove(lst[i])

You can correct this by simply changing your code like so:

for i in lst:  
    if i[0] ==1 or i[1] ==1:  
        lst.remove(lst[i])
return lst

The way your code was structured before list[i] didn't make any sense, your i was a number greater than the number of two-value-items in lst.

=D