I'm getting a TypeError: 'int' object is unsubscriptable

Question:

I got an error message from my code which says TypeError: 'int' object is unsubscriptable. After doing some research, I understand what it means, but I can’t understand why there is a problem.

I narrowed the problem down to this code:

def calcNextPos(models, xcel): # and other irrelevant parameters
    for i in range(len(models)):
        for j in range(3):
            a = xcel[i[j]]*0.5*dt*dt
            # More code after this...

I verified that xcel is a list of lists of integers when the function is called, and the indexes should not be out of bounds.

What is going wrong? How can I fix it?

Asked By: user1365256

||

Answers:

In the code for i in range(len(models)):, i is an integer. That makes a loop for values of i between 0 and a less than the length of models.

In the next two lines of the code, i[j] is used to access an array element, which doesn’t work. Did you perhaps mean models[j] instead of i[j], like so?

for i in range(len(models)):
    for j in range(3):
        a = xcel[models[j]]*0.5*dt*dt
        # More code after this...
Answered By: Andrew Brock

xcel is a two-dimensional list. The correct syntax to access the jth element of the ith sub-list is xcel[i][j], not xcel[i[j]]. The latter attempts to get the jth element of the integer i, which leads to the error described.

Answered By: Tim Pietzcker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.