Sling Academy
Home/Python/How to Fix Python TypeError: ‘int’ object is not subscriptable

How to Fix Python TypeError: ‘int’ object is not subscriptable

Last updated: January 02, 2024

Understanding the Error

Encountering a TypeError: ‘int’ object is not subscriptable in Python can be puzzling for developers, especially those new to the language. This error often happens when one mistakenly tries to access an index of an integer and treats it as an iterable like a list, string, or tuple.

Before delving into solutions, it’s important to understand what the error message means. A subscriptable object in Python is anything capable of being accessed via indices – meaning you can use square brackets to get an element, like my_list[0] for lists or my_string[1] for strings. An integer is a whole number and not an iterable object, so attempting to use an index operation on it, like my_int[0], will cause this error.

Solution Overview: Checking the Variable Type

In general, you can get through the error by following this process:

  1. Identify where the error is being thrown.
  2. Review the involved variables and check the data types.
  3. Correct the code to avoid using indexing on integers.

A code that demonstrates how to cause the mentioned error:

my_var = 42
try:
    # Incorrect indexing on an integer.
    print(my_var[0])
except TypeError as e:
    print(e)
    # Output correct value or implement other logic.
    print(my_var)

Solution 1: Debug and Modify Code

Here’s a step-by-step guide to inspecting the code and correcting the issue.

  1. Determine where in the code the error occurs.
  2. Understand the context and intended operation.
  3. Modify the code to remove indexing from the integer variable.

Example:

# Incorrect code
number = 5
print(number[0])   # This is wrong

# Corrected code
number = 5
print(number)      # This is correct

Some thoughts:

  • Advantages: Simple, no extra code necessary.
  • Limitations: Not applicable for complex data types or errors due to misplaced variables.

Solution 2: Confirm Variable Assignment

This approach ensures that the correct type of variable is being manipulated:

  1. Examine the variable assignments leading to the erroneous operation.
  2. Validate the integrity of the operations performed on the variable.
  3. Rewrite any incorrect assignments or operations.

Example:

# Possible cause of misassignment
numbers = {'a':1, 'b':2}
number = numbers    # A dictionary variable

# Mistakenly trying to index the dictionary as a whole
print(number[0])

# Instead, access the dictionary values correctly
key_lookup = 'a'
print(numbers[key_lookup])

Solution 3: Explicit Type Conversion

Converting data types to the expected iterable forms can solve the issue when a stringified integer is expected to act like a string:

  1. Locate the operation where the error is thrown.
  2. Determine if the variable type should be converted.
  3. Use cast functions like str() to convert the integer to a string if subscripting is intended.

Example:

# An integer cannot be subscripted
num = 1234

# Converting to a string allows subscripting
num_str = str(num)
print(num_str[0])

Some thoughts:

  • Advantages: Makes subscripting of number representations possible.
  • Limitations: Introduces a step of conversion which might not be always necessary or intended. It also changes the type of data being manipulated.

Next Article: Fixing AttributeError: ‘str’ object has no attribute ‘read’ in Python

Series: Common Errors in Python and How to Fix Them

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types