TypeError: 'int' object is not subscriptable
What it means
You used square brackets on a number, as if it were a list or a string. Square brackets pick items out of a sequence, and a number like 42 has no items to pick.
1. Indexing a number to get one of its digits
This raises the error
Broken
num = 4721
first_digit = num[0]
print(first_digit)
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'int' object is not subscriptable
The fix
Fixed
num = 4721
first_digit = str(num)[0] # a string has characters you can index
print(first_digit)
Output
4
Turning the number into a string with str() gives you characters you can index. Convert back with int() if you need a number.
2. A variable that holds a number, not the list you expected
This raises the error
Broken
scores = [80, 92, 75]
total = 0
for scores in scores: # the loop variable replaces the list
total += scores
print(scores[0])
Output
Traceback (most recent call last): File "<exec>", line 5, in <module> TypeError: 'int' object is not subscriptable
The fix
Fixed
scores = [80, 92, 75]
total = 0
for score in scores: # a different name keeps the list
total += score
print(scores[0], total)
Output
80 247
Reusing the list's name for the loop variable overwrote the list with its last number. A separate loop variable name keeps both.
3. Indexing one level too deep into a dictionary
This raises the error
Broken
student = {"name": "Ada", "score": 91}
print(student["score"][0])
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'int' object is not subscriptable
The fix
Fixed
student = {"name": "Ada", "score": 91}
print(student["score"])
Output
91
student["score"] is already the number 91. Index again only when the value is itself a list, a string or a dictionary.
When you see this error, check
- Print the variable and its
type()just before the failing line. - Look for a loop or assignment that reused the variable name.
- To get digits, use
str(num)[i], ornum // 10 ** i % 10to stay with numbers. - With nested data, print each level to see where the numbers start.
Related errors
All Python errors · How to read a traceback · Step through your code