List index out of range, python

I have a question, that is, the 1D list looks 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 am trying to use:

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

      

which means I want to take every last (3rd) number from List_B to List_A but it says "index out the range" so what's the problem? Many thanks for your help.

I know the append method, but I think I can't use it because my code is in a loop, the value in List_B changes 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, if I use the append method, List_A will grow to 15 items, but I need to update the value in every loop i.

+3


source to share


2 answers


The problem is List_A

, which has only one meaning. Here you are trying to change values ​​for indices 1

and a 2

list where none exist. So you get the error.

Use append

instead of declaring List_A

like[]

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

      

This can be done in one comp-list as

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

      




Editing messages -

Place 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

      

+4


source


This cycle is a 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 i

are out of range. If you are trying to populate a list you should useappend



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

      

Or more Pythonic uses a list comprehension

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

      

+3


source







All Articles