Fix TypeError: ‘int’ Object Is Not Subscriptable

Quick answer: The error means an integer reached a square-bracket expression such as value[0]. Integers do not implement item access, so trace the value before the bracket, correct the earlier assignment or conversion, and use a sequence or mapping when indexing is intended.

Python Pool infographic explaining why integers cannot be indexed and how to trace subscriptable values
The error means code used square-bracket indexing on an integer; inspect the value’s type and choose the intended sequence or mapping instead.

TypeError: 'int' object is not subscriptable means Python was asked to use square brackets on an integer. Integers do not contain indexed items, so code such as number[0] fails. Square brackets work on objects such as lists, tuples, strings, dictionaries, and many custom containers, but not on plain int values.

The fix is to look at the object before the brackets. If the code meant to read from a list, keep the list and index that list. If the code meant to inspect digits, convert the integer to a string first. If the code meant to read named fields, use a dictionary or object with the needed structure.

The official Python documentation covers TypeError, the int type, sequence types, and dictionary types.

This error often appears after a name is reused for a different kind of value, after a function returns a count instead of a list, or after input parsing changes text into an integer earlier than expected. The traceback line is the best starting point because it points to the exact bracket operation that failed.

Do not remove the brackets blindly. Brackets may be correct, but the object may be wrong. The right repair keeps the data shape consistent with the operation the code is trying to perform.

Reproduce The Error

An integer cannot be indexed. This small example catches the exception and prints the message Python raises.

number = 42

try:
    print(number[0])
except TypeError as error:
    print(error)

The message says that an int object is not subscriptable. In Python wording, subscriptable means the object supports square-bracket access.

Before changing the code, inspect the object that appears before the brackets. That tells you whether the object should be a list, a string, a dictionary, or something else.

Index The List, Not The Integer

If the goal is to read the first item from a collection, make sure the brackets are applied to the collection itself.

scores = [42, 88, 91]

first_score = scores[0]
last_score = scores[-1]

print(first_score)
print(last_score)

The list is subscriptable, and each item inside it can be an integer. The integer item is still not subscriptable on its own.

A common bug is to pull one item from a list and then accidentally index that item again. Use descriptive names such as scores and score so the difference is visible.

Python Pool infographic showing integer value, square bracket access, missing sequence protocol, and TypeError
An integer is a scalar and cannot be indexed or sliced with square brackets.

Convert An Integer To Text For Digits

If the code needs the first digit, convert the integer to a string. Strings are sequences of characters, so they support indexing.

number = 4829
digits = str(number)

first_digit = digits[0]
last_digit = digits[-1]

print(first_digit)
print(last_digit)

This returns characters, not integer digits. Convert back with int() if numeric calculation is needed after the digit is selected.

For negative numbers, handle the sign deliberately. The first character of str(-42) is -, not a digit.

Use A Dictionary For Named Fields

If the code expects a record with keys, store the data as a dictionary instead of a single integer.

student = {
    "id": 101,
    "score": 42,
}

print(student["id"])
print(student["score"])

A dictionary is subscriptable by key. An integer inside the dictionary is still an integer, so use the bracket operation at the correct level.

This pattern is common when parsing JSON, API responses, or rows from a file. Check whether the object is the whole record or one numeric field from that record.

Python Pool infographic comparing scalar integer, list container, index position, and selected item
Index the list, tuple, string, or mapping that produced the scalar rather than indexing the scalar result.

Guard Before Indexing

When input can come in several shapes, validate it before indexing. A clear exception is easier to debug than a later subscript error.

def first_item(items):
    if isinstance(items, int):
        raise TypeError("expected a sequence, got int")
    return items[0]

print(first_item(["alpha", "beta"]))

try:
    print(first_item(7))
except TypeError as error:
    print(error)

This guard is useful at function boundaries. It catches the wrong kind of input near the source of the problem.

For production code, include the accepted types in the function name, type hints, tests, or docstring so callers know what shape to pass.

Fix A Function Return Shape

Sometimes the failing line is correct, but a helper returns an integer when the caller expects a list or tuple.

def get_scores():
    return [72, 85, 91]

scores = get_scores()
top_score = scores[-1]

print(top_score)

If the function should return a count, do not index the result. If it should return a collection, update the function so it always returns that collection shape.

Tests should cover the returned type, not only the final value. A test that checks isinstance(scores, list) or directly indexes the result can catch this class of bug early.

In short, this TypeError is not about the bracket syntax itself. It is about the object before the brackets. Use lists, tuples, strings, or dictionaries when indexing is needed; keep integers for arithmetic; convert to text only when selecting digits; and validate function inputs when mixed shapes are possible.

Python Pool infographic comparing integer, dictionary key lookup, record field, and structured data access
Use a mapping when the access pattern is a named key rather than a numeric position.

Read The Failing Expression

Subscript syntax is valid for sequences, mappings, and objects that implement __getitem__(). It is not a general way to extract a digit or field from any value. Start with the exact expression and inspect the runtime type on the line before it.

value = 42
try:
    print(value[0])
except TypeError as error:
    print(type(value).__name__, error)

Trace Earlier Assignments

A variable that began as a list may be overwritten with an integer in a loop, function return, or parsing branch. Print or log type(value) at the boundary where the value changes, and give variables names that reflect whether they contain one item or a collection.

def first_item(value):
    print("received:", type(value).__name__)
    return value[0]

items = [10, 20]
print(first_item(items))
Python Pool infographic testing return values, indexing order, slices, None, and validation
Check the value returned by the previous operation, its type, indexing intent, and None handling.

Use The Correct Container

If the input should contain several values, keep it as a list or tuple and index that object. If it is a mapping, use its key. If the integer is a count, compare or calculate with it instead of indexing.

values = [10, 20, 30]
record = {"count": 3}
print(values[0])
print(record["count"])
print(record["count"] + 1)

Convert Only With A Clear Meaning

Converting an integer to a string makes digit indexing possible, but it changes the data from a number into text. Use this only when a digit-level text operation is the real requirement, and remember that negative signs and leading zeroes need their own policy.

number = 2026
digits = str(number)
print(digits[0])
print([int(digit) for digit in digits])

Python’s data model describes subscription through __getitem__(). When an integer reaches brackets, fix the value’s type and data flow instead of suppressing the TypeError.

For related indexing failures, compare list index errors, integer conversion, and string length when tracing whether the value or the index is wrong.

Frequently Asked Questions

What does int object is not subscriptable mean?

An integer was used with square brackets even though integers do not implement item access.

How do I fix this TypeError?

Find the value before the failing bracket expression, inspect its type, and correct the earlier conversion, indexing, or variable assignment.

Can I index an integer in Python?

No. Convert it to a string only when digit indexing is truly intended, or use the original list, tuple, or mapping instead.

Why does the error appear inside a loop?

A variable may be overwritten with an integer during one iteration, so trace each assignment and validate the loop input.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted