Python Error: TypeError: ‘int’ Object Is Not Subscriptable?

If TypeError: ‘int’ object is not subscriptable keeps interrupting your Python code, the issue may be caused by accessing an integer like a list, string, or dictionary. Identify the root cause and fix your code before it leads to further errors.

  • Integer indexing error detection
  • Python code debugging
  • Variable type validation fixes
  • Root cause analysis and error resolution
Talk to a Tech Consultant

Python developers often encounter error messages related to lists, dictionaries, strings, and numbers. The error message is called “TypeError: ‘int’ object is not subscriptable“. This error is caused when the script tries to index an integer.

It is typically generated when the developer treats an integer object as a list, string, tuple, or dictionary. This problem can also appear when variable types change unexpectedly, a function returns the wrong type, or you loop over the wrong data type.

Trying to call number[0] when number is an integer causes this error.

This problem may seem confusing at first, but understanding Python indexing makes it easy to solve.

In the following article, we will learn what this error is, why it happens, how to fix it, and how to avoid it, with Python examples.

What Does TypeError: ‘int’ Object Is Not Subscriptable Mean?

The error means Python is trying to use the subscript operator ([]) on an integer object that doesn’t support indexing.

In Python, subscripting lets developers access individual elements in supported objects such as lists, strings, tuples, and dictionaries.

For example:

numbers = [10, 20, 30]
print(numbers[0])

Output:

10

Here, numbers[0] works because a list supports indexing.

However, consider this example:

number = 100
print(number[0])

Output:

TypeError: ‘int’ object is not subscriptable

The error occurs because 100 is an integer, not a collection containing individually accessible elements.

Python integers represent numerical values and don’t support indexing with square brackets.

Why Does the ‘int’ Object Is Not Subscriptable Error Occur?

Several programming mistakes can cause this error. Most involve incorrect assumptions about a variable’s data type.

Attempting to Index an Integer

The most direct cause is using square brackets on an integer.

age = 25
print(age[0])

Since age contains an integer, Python cannot retrieve its first element.

Unlike strings and lists, integers do not have indexed positions.

Solution:

If you need to access individual digits, convert the integer into a string.

age = 25
first_digit = str(age)[0]
print(first_digit)

Output:

2

The result is a string. Use int() if a numerical digit is required.

Incorrect Variable Data Types

Developers sometimes expect a variable to contain a list or string, but it actually contains an integer.

data = 500
print(data[1])

The code assumes data is subscriptable.

Solution:

Inspect the variable before applying indexing.

data = 500
print(type(data))

Output:

<class ‘int’>

Once the actual type is identified, modify the code to use an appropriate operation.

Accidentally Overwriting a List Variable

A variable may initially contain a list but later be assigned an integer.

numbers = [10, 20, 30]
numbers = 50
print(numbers[0])

The second assignment replaces the list with an integer.

Solution:

Use separate variable names for different purposes.

numbers = [10, 20, 30]
total = 50
print(numbers[0])

This preserves the list and avoids unexpected type changes.

Incorrect Function Return Values

A function may return an integer when the calling code expects a collection.

def get_data():
return 100
result = get_data()
print(result[0])

The function returns an integer, so indexing fails.

Solution:

Ensure the return value matches the expected data structure.

def get_data():
return [100, 200, 300]
result = get_data()
print(result[0])

Output:

100

Alternatively, remove indexing if the function is intended to return a single numerical value.

How to Fix TypeError: ‘int’ Object Is Not Subscriptable in Python

The correct solution depends on what the program is trying to accomplish.

Method 1: Convert the Integer Into a String

If you want to retrieve individual digits, convert the number into a string.

number = 98765
first_digit = str(number)[0]
print(first_digit)

Output:

9

You can also access the final digit:

number = 98765
last_digit = str(number)[-1]
print(last_digit)

Output:

5

This approach is useful when processing identification numbers, numerical patterns, or digit-based operations.

Method 2: Convert the Integer Into a List of Digits

When you need to process each digit individually, convert the integer into a list.

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

Output:

[1, 2, 3, 4, 5]

Now indexing works:

print(digits[2])

Output:

3

For negative integers, process the absolute value if only the digits are required.

Method 3: Use Mathematical Operations Instead of Indexing

If the objective is to extract numerical digits, mathematical operations may be more appropriate.

For example, retrieve the last digit using the modulo operator.

number = 12345
last_digit = number % 10
print(last_digit)

Output:

5

To retrieve the tens digit:

number = 12345
tens_digit = (number // 10) % 10
print(tens_digit)

Output:

4

This approach avoids unnecessary string conversions when performing numerical calculations.

Method 4: Check the Variable Type Before Indexing

When working with dynamic input, inspect the value before accessing elements.

value = 100
if isinstance(value, (list, tuple, str)):
print(value[0])
else:
print("Value does not support sequence indexing")

This prevents the specific error when the value is an integer.

However, remember that not every subscriptable object is a sequence. Dictionaries, for example, use keys rather than positional indexing.

Method 5: Correct the Expected Data Structure

Sometimes the real issue is that the variable should contain a list instead of an integer.

Incorrect:

scores = 90
print(scores[0])

Correct:

scores = [90, 85, 95]
print(scores[0])

Output:

90

Choose a data structure that matches the application’s requirements rather than converting values without understanding their purpose.

How to Fix the Error When Working With Dictionaries

Dictionaries support subscripting through keys, but their values may contain integers.

For example:

employee = {
"name": "John",
"age": 30
}
print(employee["age"][0])

This produces the error because employee[“age”] returns the integer 30.

Solution:

Access the value directly.

print(employee["age"])

Output:

30

If you need the first digit of the age:

print(str(employee["age"])[0])

Output:

3

This distinction is important when working with nested dictionaries and JSON responses.

How to Fix the Error in Pandas DataFrames?

Pandas users may encounter the same error when extracting scalar values from DataFrames.

For example:

import pandas as pd
df = pd.DataFrame({
"price": [100, 200, 300]
})
value = df.loc[0, "price"]
print(value[0])

The selected value is a numerical scalar, so positional indexing is inappropriate.

Solution:

Use the scalar directly:

value = df.loc[0, "price"]
print(value)

Output:

100

If you need multiple values, select a Series or DataFrame rather than a single cell.

prices = df["price"]
print(prices.iloc[0])

Output:

100

This distinction helps avoid type-related problems during data analysis.

What is the Difference Between Subscriptable and Non-Subscriptable Objects?

In Python, subscriptable objects support element access using square brackets. Non-subscriptable objects do not provide that behavior.

Python objectSubscriptable?Example
ListYesitems[0]
TupleYesvalues[1]
StringYestext[0]
DictionaryYesdata[“key”]
IntegerNonumber[0]
FloatNoprice[0]
BooleanNoflag[0]
SetNoitems[0]

A dictionary is subscriptable through its keys, while lists, tuples, and strings commonly support positional indexing.

The important distinction is whether an object’s type implements the required subscription behavior.

How to Debug TypeError: ‘int’ Object Is Not Subscriptable

When the error occurs in a larger application, it’s often more useful to identify where the integer originated than to modify the failing line immediately.

Step 1: Read the Error Traceback

Python provides a traceback showing the file, line number, and operation that caused the exception.

For example:

File "app.py", line 8, in <module>
print(result[0])
TypeError: 'int' object is not subscriptable

Locate the indicated line and identify the variable being indexed.

Step 2: Inspect the Variable

Use type() and repr() to understand the current value.

print(type(result))
print(repr(result))

These checks reveal whether the variable contains an integer, string, list, or another object.

Step 3: Trace the Value’s Origin

Examine where the variable was assigned.

It may come from a function return value, an API response, a dictionary lookup, or a loop iteration.

Check whether earlier operations changed the expected data type.

Step 4: Apply the Appropriate Correction

After identifying the source, choose the correct fix.

Convert the value when digit access is intended, preserve the expected collection when indexing is required, or remove indexing when the value is supposed to be a scalar.

How Can You Prevent This Error in Python?

Preventing type-related errors begins with consistent data handling and readable code.

Use Meaningful Variable Names

Choose names that describe what the value should be.

For example, use employee_age for an integer and employee_ages for a list.

This reduces confusion when accessing values.

Add Type Hints

Python type hints make expected data structures clearer.

def get_scores() -> list[int]:
return [85, 90, 95]

Static type checkers can catch invalid indexing before execution.

Validate External Data

API responses, user input, and database results may not always match expected formats.

Validate important values before processing them.

def first_item(data):
if not isinstance(data, (list, tuple)):
raise TypeError("Expected a list or tuple")
return data[0]

This provides a clearer error message when an unexpected value is supplied.

Write Unit Tests

Unit tests can verify function return types and expected behavior.

def get_numbers():
return [1, 2, 3]
def test_get_numbers():
result = get_numbers()
assert isinstance(result, list)
assert result[0] == 1

Testing helps catch accidental type changes during development.

How Moon Technolabs Helps With Python Development and Error Resolution

The programs written in Python often work with complex structures, API responses, numbers, and database entries. Wrong assumptions regarding the above values may result in program errors.

The following development services related to Python are offered by Moon Technolabs: building a custom solution; application maintenance and integration.

Our developers will help you with:

  1. Python error debugging: finding TypeErrors, incorrect data structures, and runtime errors.
  2. Code optimization: making code clear and easy to maintain.
  3. API integration: validating the API response and working with different types of data.
  4. Application development: developing scalable Python-based software solutions.
  5. Testing and maintenance: implementing validation and error handling.

With the right combination of debugging and development processes, we help our customers avoid application errors.

Let Our Python Experts Resolve Your Application Errors

Don’t let Python errors slow down your business. Moon Technolabs provides professional debugging, code optimization, and error resolution services to help keep your applications reliable and efficient.

Get Python Development Support

Conclusion

TypeError: ‘int’ object is not subscriptable is raised in Python programs that try to subscript an integer with square brackets.

Whereas lists, tuples, strings, and dictionaries can be subscripted, integers cannot be subscripted.

This error usually arises due to type errors with variables, unintended assignment, function output problems, and inappropriate indexing within loops and complex data structures.

In order to resolve this issue, one needs to check the type of the variable and determine the operation to be performed, and then drop subscripting or convert the integer into another appropriate data structure.

Assigning useful names to variables, type annotations, input checking, and testing are other ways of preventing such errors.

Knowing about the data types of Python and indexing will help to resolve this error effectively.

author image

Find comprehensive resources on Python programming, frameworks, automation, data science, AI, scripting, and backend development. Whether you're a beginner or an experienced developer, this category covers practical Python concepts and coding best practices. Stay updated with the latest Python tools, libraries, and development trends.

Related Q&A

bottom_top_arrow
Chat

Call Us Now

OR
OR