3

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.

Bhargav Rao
52.5k29 gold badges129 silver badges142 bronze badges
asked Jul 20, 2015 at 18:21
2
  • List_A = [3] doesn't create a list with a length of 3, if that's what you think it did. It creates a list with a single element, whose value is 3. Commented Jul 20, 2015 at 18:24
  • Please edit your post to include the complete questions and not answers. Please add relevant examples too Commented Jul 20, 2015 at 18:27

2 Answers 2

5

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
answered Jul 20, 2015 at 18:22

Comments

4

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]
answered Jul 20, 2015 at 18:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.