PythonMastery
reference 3 min read · lesson 3 of 60 in Errors

TypeError: 'int' object is not subscriptable

1 · The lesson

read

What 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

python
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.

python
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:

python
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:

python
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 to rows by mistake, so every later rows[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 (.count returns an integer).
  • Loop variable shadowing: for data in data_list: then later data[0] when data is now an int element.

See Also

Found this useful? Share it with a friend who’s learning Python.