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?
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...
xcel
is a two-dimensional list. The correct syntax to access the j
th element of the i
th sub-list is xcel[i][j]
, not xcel[i[j]]
. The latter attempts to get the j
th element of the integer i
, which leads to the error described.
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?
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...
xcel
is a two-dimensional list. The correct syntax to access the j
th element of the i
th sub-list is xcel[i][j]
, not xcel[i[j]]
. The latter attempts to get the j
th element of the integer i
, which leads to the error described.