Hick
Hick

Reputation: 36404

indexing error in list in python

B=l.append((l[i]+A+B))

l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ?

Upvotes: 3

Views: 203

Answers (3)

Olivier Verdier
Olivier Verdier

Reputation: 49156

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.

Upvotes: 1

Daniel G
Daniel G

Reputation: 69682

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.

Upvotes: 1

zoli2k
zoli2k

Reputation: 3458

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

Upvotes: 0

Related Questions