Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list index out of range,python

I have a question, that is, I have 1D list like this:

List_A = []

and I also have another list, something like this:

List_B = [(1,2,3),(2,3,4),(3,4,5)]

Now I try to use:

for i in range(3):
List_A[i] = List_B[i][2]

which means, I want take every last (3rd) number from List_B to List_A, but it is said "index out of range", so what is the problem? Thank you very much for your helping

I know the append method but I think I can't use it, because my code is under a loop, the value in List_B changes in every step,something like:

List_A = []

for i in range(5):
List_B = [(i*1,i*2,i*3),(i*2,i*3,i*4),(i*3,i*4,i*5)]  
    for j in range(3):
        List_A[j] = List_B[j][2]

that is to say, if I use append method, the List_A will enlarge to 15 element size, but I need refresh value in every i loop.

like image 436
GuangWu Avatar asked Jun 22 '26 15:06

GuangWu


1 Answers

The problem is with List_A which has only one value. Here you are trying to change the values for the indexes 1 and 2 of the list where there is none. So you get the error.

Use append instead after declaring List_A as []

for i in range(3):
     List_A.append(List_B[i][2])

This can be done in a single list-comp as

List_A = [i[2] for i in List_B]

Post edit-

Put the initialization right after the first loop

for i in range(5):
    List_A = []                          # Here 
    List_B = [(1,2,3),(2,3,4),(3,4,5)]  
    for j in range(3):
        List_A.append(List_B[j][2])
    # Do other stuff
like image 189
Bhargav Rao Avatar answered Jun 25 '26 06:06

Bhargav Rao