TypeError: 'int' object is not subscriptable
1 · The lesson
readWhat this error means
You used square brackets (x[0], x["key"], x[1:3]) on a value that is an integer. Sequences (lists, tuples, strings, bytes) and mappings (dicts) support indexing with []. Integers don't, because an integer does not contain items.
When you see it
Traceback (most recent call last): File "main.py", line 3, in <module> first_digit = number[0] TypeError: 'int' object is not subscriptable
Why it happens
Almost always one of three things:
1. Variable shadowing. A name that used to be a list/dict got reassigned to an integer earlier in the function.
2. Wrong return type. You expected a function to return a list, but it returned a count (len(...), a sum, an ID).
3. You wanted digits of a number. Python doesn't treat 1234 as [1, 2, 3, 4]. You have to convert it explicitly.
data = [10, 20, 30] data = sum(data) # oops, now `data` is 60 print(data[0]) # TypeError: 'int' object is not subscriptable
How to fix it
To get digits of a number, convert to str first:
number = 1234 first_digit = int(str(number)[0]) # 1 all_digits = [int(d) for d in str(number)]
Stop reusing the same variable name for different types:
data = [10, 20, 30] total = sum(data) # use a new name print(data[0]) # works
Check what your function really returns. Sometimes the function returns the length when you expected the list. Read the docstring, or use print(type(result)) to check.
When you'd see this in real code
len(rows)was assigned torowsby mistake, so every laterrows[i]raises this error.- A REST API returns a numeric error code (
-1) instead of the expected list payload. - You called
.count(...)on a list to filter it (.countreturns an integer). - Loop variable shadowing:
for data in data_list:then laterdata[0]whendatais now an int element.
Related errors
- TypeError: list indices must be integers or slices, not str: the opposite mistake, indexing a list as if it were a dict.
- TypeError: 'NoneType' object is not iterable: another "wrong return type" symptom.
- TypeError: 'str' object does not support item assignment: strings are subscriptable, but they are read-only.
See Also
- All Python errors: the full index, by type and by when it happens.
- Lists (tutorial)
- Dictionaries (tutorial)
- Type conversion cheat sheet
Found this useful? Share it with a friend who’s learning Python.