List indexing error in python

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

l is a list, and I'm trying to add more value to it so that it works like an array. But it still gives me an error, like a list index is out of range. How to get rid of it?

+3
source share
3 answers

There are many problems in the code:

1) the method append does not return anything , so it makes no sense to writeB = l.append(...)

2) The double bracket is confused, the code you wrote is exactly equivalent B.append(l[i]+A+B)

3) Finally, it is obvious that the index imust be a valid index for the list l, otherwise you will get an exception IndexError.

+1
source

, i , len(l) - 1 ( Python , 0 1, len(l) - 1, len(l).

:

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

i l, , .

? . , l, , i , , len(l) - 1.

+1

The variable is igreater than or equal to the size of the array l.

0
source

Source: https://habr.com/ru/post/1740556/


All Articles