TryBugHunt

TypeError: 'int' object is not subscriptable

TypeError: 'int' object is not subscriptable in Python means you used square brackets, like x[0], on a number. Only things that hold items (strings, lists, tuples, dictionaries) can be indexed.

PythonPattern: Type errors

How do I fix TypeError: 'int' object is not subscriptable?

TypeError: 'int' object is not subscriptable means you used square brackets, like n[0], on a number. A number has no positions to index. If you want a digit, convert first: str(n)[0]. If you expected a list, find the line that reassigned the variable to a number, such as marks = len(marks).

  1. 1. Print the value's typeJust above the failing line, add print(type(x), x) for the name before the [.
  2. 2. Find the reassignmentSearch upward for a line that stored a number in the same name, and give the number its own name.
  3. 3. Use str() for digitsTo get digits from a number, index its string form: int(str(n)[0]) gives the first digit.

What does TypeError: 'int' object is not subscriptable mean?

"Subscriptable" means "you can use [ ] on it". A list has items at positions 0, 1, 2, so items[0] works. A number is a single value with no positions, so n[0] has no meaning. Usually you either wanted the digits of the number, or a variable you thought was a list now holds a number.

Why does TypeError: 'int' object is not subscriptable happen?

1. Trying to get a digit from a number

A number has no positions. Turn it into a string first; each character is one digit.

Breaks

n = 1234
first = n[0]

Works

n = 1234
first = int(str(n)[0])   # 1

2. A variable changed from a list to a number

Reusing the same name for the count replaces the list.

Breaks

marks = [70, 85, 90]
marks = len(marks)
print(marks[0])

Works

marks = [70, 85, 90]
count = len(marks)
print(marks[0])

3. A function returns a number, not a list

You indexed the result expecting a list, but the function returns one number.

Breaks

def get_total(prices):
    return sum(prices)

print(get_total([10, 20])[0])

Works

def get_total(prices):
    return sum(prices)

print(get_total([10, 20]))

How to find it in your own code

Checklist: 1) Find the name just before the [ on the failing line. 2) print(type(name), name) just above it. 3) If it is a number you did not expect, search upward for the line that assigned it. 4) If you wanted digits, use str(n)[i] or a loop with n % 10 and n // 10.

Practise type errors

None of the challenges raises this exact error yet. These practise the same kind of bug.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all type errors →