I can’t access an index from an array

Asked

Viewed 49 times

-1

Well, I am having trouble accessing the 3° index of my list. When I try to access, returns me an error of: List index out of range.

vertices = [[-1,-1,1],
            [-1,1,1],
            [1,1,1],
            [1,-1,1]]

for v in vertices:
  print(v[3])

I want to access the vertices, 1,-1,1. But I always come across this error.

  • 3

    The indexes of each v go from 0 to 2 in this example of yours. What you expect to have in 3?

  • [1,-1,1] is in vertices[3], nay v[3]. The v is each of the internal lists, with 3 numbers each.

1 answer

0


Following the values you want to receive... You must replace the access index to the vertex values, from 3 to 0.

This error (List index out of range) happens because you are trying to access an index that does not exist.

In some programming languages (e.g., Python, PHP, C#, Java), the indexes start at 0. So the vertex index representation would look like this:

índices:    0   1  2     0  1  2    0  1  2    0   1  2
vértice: [[-1, -1, 1], [-1, 1, 1], [1, 1, 1], [1, -1, 1]]

Note that index 3 does not exist, in this case.

Code:

vertices = [[-1, -1, 1],
            [-1,  1, 1],
            [ 1,  1, 1],
            [ 1, -1, 1]]

for v in vertices:
  print(v[0])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.