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

2019-02-15 12:14发布

This question already has an answer here:

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?

5条回答
走好不送
2楼-- · 2019-02-15 12:34

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楼-- · 2019-02-15 12:34

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

查看更多
唯我独甜
4楼-- · 2019-02-15 12:46

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楼-- · 2019-02-15 12:48

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.

查看更多
聊天终结者
6楼-- · 2019-02-15 12:58

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]
查看更多
登录 后发表回答