Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexing error in list in python

Tags:

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 ?

like image 845
Hick Avatar asked Sep 14 '26 15:09

Hick


2 Answers

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.

like image 54
Olivier Verdier Avatar answered Sep 16 '26 05:09

Olivier Verdier


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.

like image 40
Daniel G Avatar answered Sep 16 '26 03:09

Daniel G