[Solved] TypeError: ‘int’ Object Is Not Subscriptable in Python

  • Python raises TypeError: object is not subscriptable if you try to use indexing upon an object that is not subscriptable. To fix it you can:
    • Typecast or wrap the non-subscriptable object to a subscriptable object like a string, list, tuple or dictionary, or,
    • Remove the index call, or
    • Overwrite the __getitem__ method in your program.

[toc]

✍ Overview

Problem: How to fix “TypeError: ‘int’ Object Is Not Subscriptable” in Python?

Example:

number = int(input("Enter a number: "))
print("reversed num = ", number[::-1])

Output:

Enter a number: 123
Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 2, in <module>
    print("reversed num = ", number[::-1])
TypeError: 'int' object is not subscriptable

Have you encountered this stupid error? ?

If your answer is yes, then you are not alone. This is one of the most common errors in Python, and thousands of programmers like you come across this error in numerous projects every single month. In this tutorial, you will learn exactly why this error occurs, how to fix it, and how never to make the same mistake again. So, without further delay, let’s get started.

TypeError:’int’ object is not subscriptable

Before understanding what the above mentioned TypeError means and the reason behind its occurrence; let us dive into an important question related to TypeError:’int’ object is not subscriptable.

? What does object is not Subscriptable mean in Python?

In Python, when one object can contain another object, it is subscriptable. In simple terms, subscriptable objects. Thus Stringstupleslists, and dictionaries are subscriptable objects in Python.

?Note: In Python, subscriptable objects implement the __getitem__() method. However, non-subscriptable objects like sets, integers, etc., do not have the __getitem__ attribute.

Example:

my_list = ['Python', 'Java', 'Golang']
my_set = {'Python', 'Java', 'Golang'}
my_integer = 100
print("Is list subscriptable? ", hasattr(my_list, '__getitem__'))
print("Is set subscriptable? ", hasattr(my_set, '__getitem__'))
print("Is integer subscriptable? ", hasattr(my_integer, '__getitem__'))

Output:

Is list subscriptable?  True
Is set subscriptable?  False
Is integer subscriptable?  False

Therefore, it is clear from the above example that an integer object is not subscriptable in Python. This leads us to the next question.

? What causes TypeError:’int’ object is not subscriptable?

  • Non-subscriptable objects are not indexable, like a list, tuple, or string. As soon as you try to implement indexing upon objects that are not subscriptable, you will encounter TypeError: object is not subscriptable 
  • As an integer object, is not a subscriptable, thus if you try to use the index of an integer object then Python will throw the following error: TypeError:'int' object is not subscriptable.

Thus, in the above example, when we tried to access the index of an integer and then reverse it, Python raised – TypeError:'int' object is not subscriptable.

So, how do we fix this error? ? Let’s have a look at the methods to fix/avoid such errors.

?️ Solution 1: Typecast The Integer Object to a String Object

You can fix the error by simply converting the integer user input to a string. There are two ways of accomplishing this task:

  1. You can directly accept the user input as string, instead of an integer. However, we will not be following this method because this condition may vary according to requirements.
  2. The second way to typecast the user input from an integer to a string is to use the built-in str() method in Python.

number = int(input("Enter a number: "))
rev = str(number)
print("reversed num = ", rev[::-1])

Output:

Enter a number: 123
reversed num =  321

?️ Solution 2: Redefine __getitem__

Another work-around to our problem is to overwrite the __getitem__ method that takes one (index) argument i (in addition to the obligatory self argument) and returns the i-th value of the “container”.

class Rev:
    def __getitem__(self, i):
        return str(i)[::-1]


obj = Rev()
number = int(input("Enter a number: "))
print(obj[number])

Output:

Enter a number: 123
321

Explanation: In our case, we are overwriting the __getitem__ method to simply return the user input as a string by reversing it using its index.

In Python, Object is Not Subscriptable error occurs in numerous scenarios. Hence, let’s have a look at some other scenarios that lead to the occurrence of a similar TypeError.

⚠️ TypeError: ‘NoneType’ object is not subscriptable

The following code snippet shows the minimal example that leads to the error:

variable = None
print(variable[0])
# TypeError: 'NoneType' object is not subscriptable

Reason of Error: You set the variable to the value None. The value None is not a container object, it doesn’t contain other objects. So, the code really doesn’t make any sense—which result do you expect from the indexing operation?

Solution:

print("Method 1: Wrap the Non-Indexable values in a list")
variable = [None]
print("Output: ", variable[0])
print()
print("Method 2: Overwrite __getitem__")
class X:
    def __getitem__(self, i):
        return f"Value {i}"
variable = X()
print(variable[0])

Output:

Method 1: Wrap the Non-Indexable values in a list
Output:  None

Method 2: Overwrite __getitem__
Value 0

⚠️ TypeError: ‘builtin_function_or_method’ object is not subscriptable

Example:

def foo(li):
    if li.pop['Subject'] == 'Physics':
        print("Every action has an equal and opposite reaction.")


list1 = [{'Subject': 'Physics', 'Name': 'Newton'},
         {'Subject': 'Maths', 'Name': 'Ramanujan'},
         {'Subject': 'Economics', 'Name': 'Smith'}]
foo(list1)

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 9, in <module>
    foo(list1)
  File "D:/PycharmProjects/PythonErrors/rough.py", line 2, in foo
    if li.pop['Subject']=='Physics':
TypeError: 'builtin_function_or_method' object is not subscriptable

Solution:

Though li.pop is a valid expression in Python that results in a reference to the pop method, but in this case it doesn’t actually call that method. You need to add the open and close parentheses to call the method as shown below.

def foo(li):
    if li.pop(0)['Subject'] == 'Physics':
        print("Every action has an equal and opposite reaction.")


list1 = [{'Subject': 'Physics', 'Name': 'Newton'},
         {'Subject': 'Maths', 'Name': 'Ramanujan'},
         {'Subject': 'Economics', 'Name': 'Smith'}]
foo(list1)

# Output --> Every action has an equal and opposite reaction.

⚠️ TypeError: ‘set’ object is not subscriptable

The following code snippet shows the minimal example that leads to the error:

my_set = {111, 222, 333}
print(my_set[2])

# TypeError: 'set' object is not subscriptable

Reason: set is not a subscriptable object in Python. Hence, you cannot access its elements using their index.

Solution:

  1. Convert the set to a list, or,
  2. overwrite the __getitem__ method.
my_set = {111, 222, 333}

# Method 1
my_list = list(my_set)
print("Method 1 Output: ", my_list[2])


# Method 2
class Convert:
    def __getitem__(self, i):
        return [*i, ][2]


obj = Convert()
print("Method 2 Output: ", obj[my_set])

Output:

Method 1 Output:  111
Method 2 Output:  111

Conclusion

Here are some recommended articles that might help you further:

I hope this article helped you. Please subscribe and stay tuned for more exciting articles in the future. Happy learning! ?

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!