(Python) List index out of range - iteration [duplicate]

£可爱£侵袭症+ 提交于 2019-11-30 19:08:36

问题


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



来源:https://stackoverflow.com/questions/20819504/python-list-index-out-of-range-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!