Solve ‘Int’ Object Is Not Subscriptable In Python
- Use Strings or Lists Instead of Integers
- Check Variable Types
- Review Code Logic:
Let us study them in detail
Use Strings or Lists Instead of Integers
In Python, subscript notation is applicable to strings and lists. So we can convert integer to a string or list before using subscript notation.
Python3
# Converting integer to string and using subscript notation number = 42 number_str = str (number) print (number_str[ 0 ]) |
4
Check Variable Types
We need to make sure that the variable we are using is of the expected type we want it to be. If it’s supposed to be a sequence (string or list), make sure it is not mistakenly assigned an integer value.
Python3
# Checking variable type before using subscript notation number = 42 if isinstance (number, ( str , list )): print (number[ 0 ]) else : print ( f "Error: Variable type '{type(number).__name__}' is not subscriptable." ) |
Error: Variable type 'int' is not subscriptable.
Review Code Logic
Examine your code logic to determine if subscript notation is genuinely necessary. If not, revise the code to avoid subscripting integers.
Python3
# Reviewing code logic to avoid subscripting integers number = 42 number_str = str (number) print (number_str[ 0 ]) |
4
Fix ‘Int’ Object is Not Subscriptable in Python
In this article, we will study how to fix ‘int’ object that is not subscriptable in Python. But before that let us understand why it occurs and what it means.
What is ‘Int’ Object Is Not Subscriptable Error?
The error ‘int’ object is not subscriptable occurs when you attempt to use indexing or slicing on an integer, a data type that doesn’t support these operations.
As we know integer in Python is a data type that represents a whole number. Unlike lists or dictionaries, integers do not hold a sequence of elements and therefore do not support indexing or slicing.
For example, if x = 42 (an integer), and we try to do something like x[0], it’s an attempt to access the first element of x as if x were a list or a tuple. Since integers don’t contain a collection of items, this operation isn’t valid and you get a TypeError: ‘int’ object is not subscriptable.
Example
Python3
# Example causing 'int' object is not subscriptable error x = 42 # Attempting to use subscript notation on an integer print (x[ 0 ]) |
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
print(number[0])
TypeError: 'int' object is not subscriptable