The TypeError: 'int' object is not subscriptable occurs when you try to treat an integer as if it were a list, string, or another subscriptable object. In Python, only objects like lists, strings, tuples, and dictionaries can be subscripted (i.e., accessed using square brackets to retrieve elements).

Here’s how you can troubleshoot and fix this error:

1. Check the Variable Type

Ensure that the variable you are trying to subscript is indeed a list, string, tuple, or dictionary and not an integer.

my_list = [1, 2, 3]
value = my_list[0]  # This is valid because my_list is a list

2. Avoid Subscribing Integers

If you accidentally try to subscript an integer, you need to correct the code so that the integer is not treated like a list or string.

Problematic Code:

num = 10
print(num[0])  # This will cause the TypeError

Corrected Code:

num = 10
print(str(num)[0])  # Convert the integer to a string if you want to access digits

3. Trace Back the Variable Assignment

Sometimes, a variable might accidentally be reassigned as an integer, leading to this error. Trace back where the variable is defined and ensure it retains the correct type.

Example:

my_dict = {'key': [1, 2, 3]}
my_dict = 5  # This is incorrect if you later try to access my_dict['key']
print(my_dict['key'])  # TypeError will be raised

Corrected Code:

my_dict = {'key': [1, 2, 3]}
print(my_dict['key'])  # This will work fine

4. Check Function Returns

If you’re calling a function that you expect to return a list, string, etc., but it returns an integer, you might encounter this error. Make sure the function returns the expected type.

Example:

def get_data():
    return 5  # This should return a list or string

data = get_data()
print(data[0])  # This will cause the TypeError

Corrected Code:

def get_data():
    return [5, 6, 7]  # Now, it returns a list

data = get_data()
print(data[0])  # This will work fine

By following these steps, you should be able to identify and fix the cause of the TypeError: 'int' object is not subscriptable.

Simon

102 Articles

I love talking about tech.