When working in Python, receiving errors from our programs can be frustrating.
One such error is when you get a TypeError because you try to access the index of an object that is not subscriptable or doesn’t support indexing. Such TypeErrors include:
- TypeError: ‘int’ object does not support indexing
- TypeError: list indices must be integers or slices, not str
- TypeError: ‘int’ object is not subscriptable
- TypeError: ‘set’ object is not subscriptable
- TypeError: ‘list’ object is not callable
At the heart of this error is the fact that you are trying to access an index where the object does not support indexing.
These errors can occur if you aren’t careful with how you name your variables.
For example, certain names are keywords in Python and it is possible that you can use these as variable names.
One example is if you use the variable name “list” for a list variable.
Then, if you try to use list later on in your program to convert an object to a list, you will get an error.
list = [1, 2, 3]
#other code
new_list = list({0, 1, 2})
#Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Another example is if you have variables which are integers and you try to access some index of the integer.
a = 5
print(a[0])
#Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
In all of these cases, you just need to be careful with the object types you are using and if necessary, convert your objects objects which do support indexing like lists.
Hopefully this article has been useful for you to learn how to solve the error when you receive a TypeError and your object does not support indexing in Python.
Leave a Reply