开发者

indexing error in list in python

开发者 https://www.devze.com 2022-12-26 14:34 出处:网络
B=l.append((l[i]+A+B)) l is a list here and i am trying to append into it more value f开发者_开发知识库or it to act as an array . But its still giving me error like list index out of range. How to g
B=l.append((l[i]+A+B))

l is a list here and i am trying to append into it more value f开发者_开发知识库or it to act as an array . But its still giving me error like list index out of range . How to get rid of it ?


There are many problems in your code:

1) the append method does not return anything, so it does not make sense to write B = l.append(...)

2) The double parenthesis are confusing, the code you wrote is exactly equivalent to B.append(l[i]+A+B)

3) Finally, obviously, the index i must be a valid index for the list l, otherwise you will get an IndexError exception.


List index out of range means that i is greater than len(l) - 1 (since Python, and many other programming languages, use indexing that starts at 0 instead of 1, the last item in the list has index len(l) - 1, not just len(l).

Try debugging like so:

try:
    B = l.append((l[i] + A + B))
except IndexError:
    print "Appending from index", i, "to list l of length:", len(l)
    raise

This will tell you the value of i and the length of l when the append fails so you can search for the problem.

Is this in a loop? It may help to show us the code of the loop. It could be that, even though you're increasing the length of l by appending to it, you're increasing i even faster, so that it eventually gets to be bigger than len(l) - 1.


Variable i is larger or equal to the size of the l array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号