简体   繁体   中英

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.

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

This loop is the problem

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

You can only access List_A[0] , the rest of the values of i are out of range. If you are trying to populate the list, you should use append

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

Or more Pythonic use a list comprehension

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM