Jonathan H Jonathan H - 1 year ago 74
Python Question

list index out of bounds for not the obvious reason numpy

I'm not sure why but I keep getting this error, even though the list index does not exceed the number of indexes. The code getting this error is below:

normalisedFaces = np.array([])
for f in range(len(vertextNormalIndices)):
nF1 = vecNormals[vertextNormalIndices[f][0][0]]
nF2 = vecNormals[vertextNormalIndices[f][1][0]]
nF3 = vecNormals[vertextNormalIndices[f][2][0]]
normalisedFaces = np.hstack((normalisedFaces,(np.add(nF1,np.add(nF2,nF3))/ 3)))
print(f)
time.sleep(3)
print(normalisedFaces[f])


My only guess is that I'm reaching the end of the max size of an array(?) For this example, the loop has the range of 529 , but the error comes up when I reach 519. If I change the loop to something like:

for f in range(len(vertextNormalIndices)-200):


Then it reaches the end of the range (so, in this case: 329).

How would one go about fixing this? If possible, I'd prefer not to have to nest this loop and have to split-up the size of each array to e.g. %max==300

Any guidance would be greatly appreciated

I've attached a screenshot of the error here:
enter image description here

The last 8 indexes of vertexNormalIndices: (So, gets the first number of each row e.g. 278, 195, 281)

enter image description here

Answer Source

Per your comments, and looking at your traceback, the error is in this line:
nF1 = vecNormals[vertextNormalIndices[f][0][0]]

So, the error must be that either vertextNormalIndices[519] or vertextNormalIndices[519][0] is an empty list - try printing them out in the loop.

As an aside:

The 'Pythonic' way to iterate through a list is to do it directly, and if you also need to get the index of each element, you should use enumerate:

normalisedFaces = np.array([])
for f, vertexNormalIndex in enumerate(vertextNormalIndices):
    nF1 = vecNormals[vertextNormalIndices[0][0]]
    nF2 = vecNormals[vertextNormalIndices[1][0]]
    nF3 = vecNormals[vertextNormalIndices[2][0]]
    normalisedFaces = np.hstack((normalisedFaces,(np.add(nF1,np.add(nF2,nF3))/ 3)))
    print(f)
time.sleep(3)
print(normalisedFaces[f])