The Python error «TypeError: ‘int’ object is not subscriptable» occurs when you try to treat an integer like a subscriptable object.
In Python, a subscriptable object is one you can “subscript” or iterate over.
You can iterate over a string, list, tuple, or even dictionary. But it is not possible to iterate over an integer or set of numbers.
So, if you get this error, it means you’re trying to iterate over an integer or you’re treating an integer as an array.
In the example below, I wrote the date of birth (dob
variable) in the ddmmyy format. I tried to get the month of birth but it didn’t work. It threw the error “TypeError: ‘int’ object is not subscriptable”:
dob = 21031999
mob = dob[2:4]
print(mob)
# Output: Traceback (most recent call last):
# File "int_not_subable..py", line 2, in <module>
# mob = dob[2:4]
# TypeError: 'int' object is not subscriptable
How to Fix the «TypeError: ‘int’ object is not subscriptable» Error
To fix this error, you need to convert the integer to an iterable data type, for example, a string.
And if you’re getting the error because you converted something to an integer, then you need to change it back to what it was. For example, a string, tuple, list, and so on.
In the code that threw the error above, I was able to get it to work by converting the dob
variable to a string:
dob = "21031999"
mob = dob[2:4]
print(mob)
# Output: 03
If you’re getting the error after converting something to an integer, it means you need to convert it back to string or leave it as it is.
In the example below, I wrote a Python program that prints the date of birth in the ddmmyy format. But it returns an error:
name = input("What is your name? ")
dob = int(input("What is your date of birth in the ddmmyy order? "))
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")
#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Traceback (most recent call last):
# File "int_not_subable.py", line 12, in <module>
# dd = dob[0:2]
# TypeError: 'int' object is not subscriptable
Looking through the code, I remembered that input returns a string, so I don’t need to convert the result of the user’s date of birth input to an integer. That fixes the error:
name = input("What is your name? ")
dob = input("What is your date of birth in the ddmmyy order? ")
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")
#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Hi, John Doe,
# Your date of birth is 01
# Month of birth is 01
# And year of birth is 1970.
Conclusion
In this article, you learned what causes the «TypeError: ‘int’ object is not subscriptable» error in Python and how to fix it.
If you are getting this error, it means you’re treating an integer as iterable data. Integers are not iterable, so you need to use a different data type or convert the integer to an iterable data type.
And if the error occurs because you’ve converted something to an integer, then you need to change it back to that iterable data type.
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Typeerror: type object is not subscriptable error occurs while accessing type object with index. Actually only those python objects which implements __getitems__() function are subscriptable. In this article, we will first see the root cause for this error. We will also explore how practically we can check which object is subscriptable and which is not. At last but not least, we will see some real scenarios where we get this error. So let’s start the journey.
Typeerror: type object is not subscriptable ( Fundamental Cause) –
The root cause for this type object is not subscriptable python error is invoking type object by indexing. Let’s understand with some practical scenarios.
var_list=[1,2,3]
var=type(var_list)
var[0]
Here var is a type python object. In the place of same, the list is python subscriptable object. Hence we can invoke it via index. Moreover, Here is the implementation –
var_list=[1,2,3]
var=type(var_list)
var_list[0]
The best way to fix this error is using correct object for indexing. Let’s understand with one example.
The fix is calling var[0] in the place of var_type[0] . Here ‘var’ is the correct object. It is a ‘str’ type object which is subscriptible python object.
How to check python object is subscriptable ?
Most importantly, As I explained clearly, Only those object which contains __getitems__() method in its object ( blueprint of its class) is subscriptible. Let’s see any subscriptible object and its internal method-
print(dir(var))
The output is –
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Firstly, As the internal method __getitem__() is available in the implementation of the object of var( list) hence it is subscriptible and that is why we are not getting any error while invoking the object with indexes. Hope this article is helpful for your doubt.
Similar Errors-
Typeerror int object is not subscriptable : Step By Step Fix
Typeerror nonetype object is not subscriptable : How to Fix ?
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
In this post, we will learn how to fix TypeError:object is not subscriptable error in Python. The TypeError is raised when trying to use an illegal operation on non subscriptable objects(set,int,float) or does not have this functionally. Python throws the TypeError object is not subscriptable if We use indexing with the square bracket notation on an object that is not indexable.
1.TypeError:object is not subscriptable Python
In this Python program example, accessing the integer variable values, accessing with the square bracket notation and since is not indexable.
number = 56789 print( number[0])
Output
print( number[0]) TypeError: 'int' object is not subscriptable
Solution TypeError:object is not subscriptable Python
We have to access the integer variable without index notation.Let us understand with the below example
number = 56789
print( ‘The value is :’,number)
Output
- TypeError:NoneType object is not subscriptable
- ValueError:Cannot convert non-finite values (NA or inf) to integer
- Fix ValueError: could not convert string to float
- Fixed Typeerror: nonetype object is not iterable Python
- ValueError:Cannot convert non-finite values (NA or inf) to integer
2.TypeError:object is not subscriptable set
We can’t access the set element by using the index notation.Running the below code will throw TypeError.To solve this error We have to use for loop to iterate over the set and display a single value.The Python object strings, lists, tuples, and dictionaries are subscribable their elements can be accessed using the index notation.
mySet = {3,6,9,12,15,18,121} print(mySet[0])
Output
print(mySet[0]) TypeError: 'set' object is not subscriptable
Solution object is not subscriptable set
In this example we have for loop to iterate over the set and display each element in the set.
mySet = {3,6,9,12,15}
for inx in mySet:
print(inx,end=”,”)
Output
3.TypeError:object is not subscriptable Pandas
In this example, we are finding the sum of Pandas dataframe column “Marks” that has int type. While applying the Lambda function on the ‘Marks’ column using index notation or subscript operator and encountering with TypeError: ‘int’ object is not subscriptable in Pandas.
import pandas as pd data = { 'Name': ['Jack', 'Jack', 'Max', 'David'], 'Marks':[97,97,100,100], 'Subject': ['Math', 'Math', 'Math', 'Phy'] } dfobj = pd.DataFrame(data) print(dfobj.dtypes) MarksGross = lambda x: int(x[1]) dfobj.Marks = dfobj.Marks.apply(MarksGross) Print(dfobj.Marks.sum())
Output
MarksGross = lambda x: int(x[1]) TypeError: 'int' object is not subscriptable
4. How to fix TypeError: int object is not Subscriptable Pandas
To solve Type Error with Pandas dataframe, We have not applied the lambda function using index notation instead use int(x) pass value of x inside () brackets.
import pandas as pd data = { 'Name': ['Jack', 'Jack', 'Max', 'David'], 'Marks':[97,97,100,100], 'Subject': ['Math', 'Math', 'Math', 'Phy'] } dfobj = pd.DataFrame(data) print(dfobj.dtypes) MarksGross = lambda x: int(x) dfobj.Marks = dfobj.Marks.apply(MarksGross) print(dfobj.Marks.sum())
Output
Name object Marks int64 Subject object dtype: object 394
Introduction
Some of the objects in python are subscriptable. This means that they hold and hold other objects, but an integer is not a subscriptable object. We use Integers used to store whole number values in python. If we treat an integer as a subscriptable object, it will raise an error. So, we will be discussing the particular type of error that we get while writing the code in python, i.e., TypeError: ‘int’ object is not subscriptable. We will also discuss the various methods to overcome this error.
What is TypeError?
The TypeError occurs when you try to operate on a value that does not support that operation. Let us understand with the help of an example:
Suppose we try to concatenate a string and an integer using the ‘+’ operator. Here, we will see a TypeError
because the +
operation is not allowed between the two objects that are of different types.
#example of typeError S = "Latracal Solutions" number = 4 print(S + number)
Output:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(S + number)
TypeError: can only concatenate str (not "int") to str
Explanation:
Here, we have taken a string ‘Latracal Solutions” and taken a number. After that, in the print statement, we try to add them. As a result: TypeError occurred.
What is ‘int’ object is not subscriptable?
When we try to concatenate string and integer values, this message tells us that we treat an integer as a subscriptable object. An integer is not a subscriptable object. The objects that contain other objects or data types, like strings, lists, tuples, and dictionaries, are subscriptable. Let us take an example :
1. Number: typeerror: ‘int’ object is not subscriptable
#example of integer which shows a Typeerror number = 1500 print(number[0])
output:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(number[0])
TypeError: 'int' object is not subscriptable
Explanation:
Here, we have taken a number and tried to print the through indexing, but it shows type error as integers are not subscriptable.
2. List: typeerror: ‘int’ object is not subscriptable
This TyperError problem doesn’t occur in the list as it is a subscriptable object. We can easily perform operations like slicing and indexing.
#list example which will run correctly Names = ["Latracal" , " Solutions", "Python"] print(Names[1])
Output:
Solutions
Explanation:
Here firstly, we have taken the list of names and accessed it with the help of indexing. So it shows the output as Solutions.
Daily Life Example of How typeerror: ‘int’ object is not subscriptable can Occur
Let us take an easy and daily life example of your date of birth, written in date, month, and year. We will write a program to take the user’s input and print out the date, month, and year separately.
#Our program begins from here Date_of_birth = int(input("what is your birth date?")) birth_date = Date_of_birth[0:2] birth_month = Date_of_birth[2:4] birth_year = Date_of_birth[4:8] print(" birth_date:",birth_date) print("birth_month:",birth_month) print("birth_year:",birth_year)
Output:
what is your birth date?31082000
Traceback (most recent call last):
File "C:/Users/lenovo/Desktop/fsgedg.py", line 3, in <module>
birth_date = Date_of_birth[0:2]
TypeError: 'int' object is not subscriptable
Explanation:
Here firstly, we have taken the program for printing the date of birth separately with the help of indexing. Secondly, we have taken the integer input of date of birth in the form of a date, month, and year. Thirdly, we have separated the date, month, and year through indexing, and after that, we print them separately, but we get the output ad TypeError: ‘int’ object is not subscriptable. As we studied above, the integer object is not subscriptable.
Solution of TypeError: ‘int’ object is not subscriptable
We will make the same program of printing data of birth by taking input from the user. In that program, we have converted the date of birth as an integer, so we could not perform operations like indexing and slicing.
To solve this problem now, we will remove the int() statement from our code and run the same code.
#remove int() from the input() Date_of_birth = input("what is your birth date?") birth_date = Date_of_birth[0:2] birth_month = Date_of_birth[2:4] birth_year = Date_of_birth[4:8] print(" birth_date:",birth_date) print("birth_month:",birth_month) print("birth_year:",birth_year)
Output:
what is your birth date?31082000
birth_date: 31
birth_month: 08
birth_year: 2000
Explanation:
Here, we have just taken the input into the string by just removing the int(), and now we can do indexing and slicing in it easily as it became a list that is subscriptable, so no error arises.
Must Read
Conclusion: Typeerror: ‘int’ object is not subscriptable
We have learned all key points about the TypeError: ‘int’ object is not subscriptable. There are objects like list, tuple, strings, and dictionaries which are subscriptable. This error occurs when you try to do indexing or slicing in an integer.
Suppose we need to perform operations like indexing and slicing on integers. Firstly, we have to convert the integer into a string, list, tuple, or dictionary.
Now you can easily the solve this python TypeError like an smart coder.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!
Table of Contents
- ◈ Introduction
- ➥ What Does Object Not Subscriptable Mean?
- ➥ What is a TypeError In Python?
- ➥ What is: TypeError:’int’ object is not subscriptable?
- ✨ Scenario 1: Trying To Access Index Of An Integer Object
- ✯ Method 1: Convert Integer Object to a String Object
- ✯ Method 2: Overwrite the __getitem__ Method
- ✨ Scenario 2: Treating an Integer as a List
- Conclusion
◈ Introduction
In this article, we will be discussing certain type of error in Python. To be more specific we will be discussing the reason behind the occurrence of : TypeError: 'int' Object Is Not Subscriptable
in Python and the methods to overcome such errors.
Let’s have a look at an example which demonstrates the occurrence of such errors.
Example: Consider the following program:
num = int(input(«Enter a 3 digit number? «)) sum_digit = num[0]+num[1]+num[2] print(sum_digit) |
Output:
Traceback (most recent call last): File «D:/PycharmProjects/pythonProject1/TypeError Not Subscriptable.py», line 7, in <module> sum_digit = num[0]+num[1]+num[2] TypeError: ‘int’ object is not subscriptable |
If you have come across a similar bug/error, then it must have been really frustrating! 😩
But it also brings us to a list of questions:
- What does object not Subscriptable mean?
- What is a
TypeError
? - What is
TypeError:'int' object is not subscriptable
? - How do I fix:
TypeError:'int' object is not subscriptable
?
Hence, without further delay let us discover the answers to our questions and then solve our problem.
➥ What Does Object Not Subscriptable Mean?
In simple terms, a subscriptable object in Python is an object that can contain other objects, i.e., the objects which are containers can be termed as subscriptable objects. Strings
, tuples
, lists
and dictionaries
are examples of subscriptable objects in Python.
➟ Why is Integer not a subscriptable Object?
Integers are whole numbers. They cannot contain other objects within them. Further, subscriptable objects implement the __getitem__()
method and integer objects do not implement the __getitem__()
method.
A TypeError
is raised when a certain operation is applied to an object of an incorrect type. For example, if you try to add a string object and an integer object using the +
operator, then you will encounter a TypeError
because the +
operation is not allowed between the two objects that are f different types.
Example:
Output:
TypeError: can only concatenate str (not «int») to str |
➥ What is: TypeError:’int’ object is not subscriptable?
- You will encounter
TypeError: object is not subscriptable
in Python when you try to use indexing on an object that is not subscriptable. - Since integer is not a subscriptable object, thus if you try to use indexing upon an integer object then Python will throw the following error:
TypeError:'int' object is not subscriptable
.
That brings us to our next questions:- What are some of the scenarios where we come across TypeError:'int' object is not subscriptable
and how can we fix it?
To answer the above questions, let us visualize the occurrence and solution to this kind of TypeError
with help of examples.
✨ Scenario 1: Trying To Access Index Of An Integer Object
We have already discussed the problem statement in the introduction section of this article where we tried to find the sum of all the digits of a three-digit number.
However, we got TypeError: object is not subscriptable
in our futile attempt to derive the sum. The reason was: we treated the integer object num
as a container object and tried to access it using its indices.
Now, it’s time to make amendments and make our program work! 😃
The Solution:
✯ Method 1: Convert Integer Object to a String Object
A simple solution to our problem is:
- accept the user input
num
as a string, - Each digit can now be accessed using their index now as they are strings. Typecast each digit string to an integer and calculate the sum.
num = input(«Enter a 3 digit number? «) sum_digit = (int(num[0]) + int(num[1]) + int(num[2])) print(sum_digit) |
Output:
Enter a 3 digit number? 754 16 |
✯ Method 2: Overwrite the __getitem__ Method
Another approach to solving the non-subscriptable TypeError
is to redefine the __getitem__
method in the code itself as shown below:
class Subs: def __getitem__(self, item): return int(item) obj = Subs() num = input(«Enter a 3 digit number? «) print(obj[num[0]] + obj[num[1]] + obj[num[2]]) |
Output:
Enter a 3 digit number? 546 15 |
Explanation:
In this case, we defined the __getitem__ method in our code and made it return each digit of the three-digit number in the form of an integer.
✨ Scenario 2: Treating an Integer as a List
Given below is another scenario which raises – TypeError:'int' object is not subscriptable
.
item = input(«Enter item name : «) price = input(«Enter item price : «) x = 0 int(x[price]) discounted_Price = x—3000 print («Price of an «,item, «is Rs.»,discounted_Price) |
Output:
Enter item name : iPhone 12 Enter item price : 79900 Traceback (most recent call last): File «D:/PycharmProjects/pythonProject1/TypeError Not Subscriptable.py», line 4, in <module> int(x[price]) TypeError: ‘int’ object is not subscriptable Process finished with exit code 1 |
In the above program, price
is an integer value, however we tried to use it as a list by using its index. Thus we got the error!
The Solution:
The solution is pretty straightforward in this case. You just have to avoid using the integer object as a container type object.
item = input(«Enter item name : «) price = input(«Enter item price : «) x = (int(price)) discounted_Price = x — 3000 print(«Price of an «, item, «is Rs.», discounted_Price) |
Output:
Enter item name : iPhone 12 Enter item price : 79900 Price of an iPhone 12 is Rs. 76900 Process finished with exit code 0 |
Conclusion
We learned some key points about how to deal with TypeError:'int' object is not subscriptable
in Python. To avoid these errors in your code, remember:
Python raises TypeError: object is not subscriptable
if you use indexing, i.e., the square bracket notation with a non-subscriptable object . To fix it you can:
- wrap the non-subscriptable objects into a container data type as a string, list, tuple or dictionary, or,
- by removing the index call, or
- by defining the
__getitem__
method in your code.
I hope this article helped! Please subscribe and stay tuned for more articles in the future. Happy learning! 📚
Table of Contents
Hide
- What is Subscriptable in Python?
- How do you make an object Subscriptable?
- How to Fix TypeError: ‘int’ object is not subscriptable?
- Solution
- Conclusion
In Python, we use Integers to store the whole numbers, and it is not a subscriptable object. If you treat an integer like a subscriptable object, the Python interpreter will raise TypeError: ‘int’ object is not subscriptable.
In this tutorial, we will learn what ‘int’ object is is not subscriptable error means and how to resolve this TypeError in your program with examples.
“Subscriptable” means that you’re trying to access an element of the object. The elements are usually accessed using indexing since it is the same as a mathematical notation that uses actual subscripts.
How do you make an object Subscriptable?
In Python, any objects that implement the __getitem__
method in the class definition are called subscriptable objects, and by using the __getitem__
method, we can access the elements of the object.
For example, strings, lists, dictionaries, tuples are all subscriptable objects. We can retrieve the items from these objects using indexing.
Note: Python doesn't allow to subscript the NoneType if you do Python will raise TypeError: 'NoneType' object is not subscriptable
How to Fix TypeError: ‘int’ object is not subscriptable?
Let us take a small example to read the birth date from the user and slice the day, months and year values into separate lines.
birth_date = int(input("Please enter your birthdate in the format of (mmddyyyy) "))
birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]
print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)
If you look at the above program, we are reading the user birth date as an input parameter in the mmddyy format.
Then to retrieve the values of the day, month and year from the user input, we use slicing and store it into a variable.
When we run the code, Python will raise a TypeError: ‘int’ object is not subscriptable.
Please enter your birthdate in the format of (mmddyyyy) 01302004
Traceback (most recent call last):
File "C:PersonalIJSCodemain.py", line 3, in <module>
birth_month = birth_date[0:2]
TypeError: 'int' object is not subscriptable
Solution
In our example, we are reading the birth date as input from the user and the value is converted to an integer.
The integer values cannot be accessed using slicing or indexing, and if we do that, we get the TypeError.
To solve this issue, we can remove the int() conversion while reading the input from the string. So now the birth_date will be of type string, and we can use slicing or indexing on the string variable.
Let’s correct our example and run the code.
birth_date = input("Please enter your birthdate in the format of (mmddyyyy) ")
birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]
print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)
Output
Please enter your birthdate in the format of (mmddyyyy) 01302004
Birth Month: 01
Birth Day: 30
Birth Year: 2004
The code runs successfully since the int() conversion is removed from the code, and slicing works perfectly on the string object to extract a day, month and year.
Conclusion
The TypeError: ‘int’ object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects.
The issue can be resolved by removing any indexing or slicing to access the values of the integer object. If you still need to perform indexing or slicing on integer objects, you need to first convert that into strings or lists and then perform this operation.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
type
is a reserved keyword in Python. If print the
type
keyword, we get an object by name
<class type>
, we can also pass a data object to the
type(data_object)
to the
type()
function and get the data type of the object. If we treated a value returned by the
type()
function as a list object and try to perform indexing on that value, we will encounter the
TypeError: 'type' object is not subscriptable
.
In this Python guide, we will discuss this error in detail and learn how to solve it. We will also walk through a common example where you may encounter this error.
So without further ado, let’s get started with this error.
TypeError: 'type' object is not subscriptable
is a standard Python error, and like other error statements, it is divided into two parts.
-
Exception Type (
TypeError
)
-
Error Message (
'type' object is not subscriptable
)
1. TypeError
Type Error is a standard Python exception type, it occurs in Python we perform an invalid operation on a
Python data type
object. Performing an addition or concatenation operation between an integer value and a string value is a common Python TypeError exception error.
2. ‘type’ object is not subscriptable.
In Python, there are 3 standard objects which are subscriptable, list, tuples, and string. All these three objects support indexing, which allows us to perform the square bracket notation to access the individual elements or characters from these data-type objects.
Example
# python string
string = "Hello"
# python tuple
tuple_ = (1,2,3,4)
# python list
list_= [1,2,3,4]
# acessing string tuple and list with indexing
print(string[0]) #H
print(tuple_[1]) #2
print(list_[2]) #3
But if we perform the indexing notation on a value that is returned by the
type()
function, we will receive the Error Message
'type' object is not subscriptable
.
This Error message is simply telling us that we are performing a subscriptable notation like indexing on the
'type'
object, and the
'type'
object does not support indexing or
subscriptable
.
Error Example
name ="Rahul"
#data type of name
name_dt = type(name) #<class 'str'>
# performing indexing on type object
print(name_dt[0])
Output
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(name_dt[0])
TypeError: 'type' object is not subscriptable
Break the code
In this example, we are receiving the error at line 7 because we are performing indexing on
name_dt
variable which value is
<class 'str'>
and its data type is
<class 'type'>
. And when we perform an indexing operation on a
'type'
object we receive the
TypeError: 'type' object is not subscriptable
error.
Python «TypeError: ‘type’
object is not subscriptable
» Common Scenario.
Many new programmers encounter this error when they use the same name to store the string value and the data type of string returned by the
type()
function.
Example
# string
name = "Rahul"
# data type of name
name = type(name)
print("The Data type of name is: ", name)
print('The first character of name is: ', name[0])
Output
The Data type of name is: <class 'str'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
print('The first character of name is: ', name[0])
TypeError: 'type' object is not subscriptable
Break the code
In this example, we are encountering the error in line 8 with
print('The first chracter of name is: ', name[0])
statement. This is because in line 5 we changed the value of
name
to
<class 'str'>
by assigning
type(name)
statement.
After that statement, the value of the name became
<class 'str'>
and its type became
<class 'type'>
. And when we try to access the first letter of value
'Rahul'
using
name[0]
statement, we got the error.
Solution
The solution for the above problem is very simple. All we need to do is provide the different variable names to the
type(name)
value.
# string
name = "Rahul"
# data type of name
name_dt = type(name)
print("The Data type of name is:", name_dt)
print('The first character of name is: ', name[0])
Output
The Data type of name is: <class 'str'>
The first character of name is: R
Conclusion
In this Python tutorial, we discussed the
TypeError: 'type' object is not subscriptable
error. This is a very common error and can be debugged with ease if you know how to read the errors. It occurs when we perform the indexing operation on a
type
Python object. To debug this problem, we need to make sure that we are not using indexing on the
type
object.
If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.
People are also reading:
-
Python IndentationError: unindent does not match any outer indentation level Solution
-
Input Output (I/O) and Import in Python
-
Python TypeError: cannot unpack non-iterable NoneType object Solution
-
Move File in Python: A Complete Guide
-
Python TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’ Solution
-
What is Tornado in Python?
-
Python TypeError: can only concatenate list (not “int”) to list Solution
-
Difference between Python List append and extend method
-
Python AttributeError: ‘list’ object has no attribute ‘split’ Solution
-
Chat Room Application in Python
Object Is Not Subscriptable
Overview
Example errors:
TypeError: object is not subscriptable
Specific examples:
TypeError: 'type' object is not subscriptable
TypeError: 'function' object is not subscriptable
Traceback (most recent call last):
File "afile.py", line , in aMethod
map[value]
TypeError: 'type' object is not subscriptable
This problem is caused by trying to access an object that cannot be indexed as though it can be accessed via an index.
For example, in the above error, the code is trying to access map[value]
but map
is already a built-in type that doesn’t support accessing indexes.
You would get a similar error if you tried to call print[42]
, because print
is a built-in function.
Initial Steps Overview
-
Check for built-in words in the given line
-
Check for reserved words in the given line
-
Check you are not trying to index a function
Detailed Steps
1) Check for built-in words in the given line
In the above error, we see Python shows the line
This is saying that the part just before [value]
can not be subscripted (or indexed). In this particular instance, the problem is that the word map
is already a builtin identifier used by Python and it has not been redefined by us to contain a type that subscripts.
You can see a full list of built-in identifiers via the following code:
# Python 3.0
import builtins
dir(builtins)
# For Python 2.0
import __builtin__
dir(__builtin__)
2) Check for instances of the following reserved words
It may also be that you are trying to subscript a keyword that is reserved by Python True
, False
or None
>>> True[0]
<stdin>:1: SyntaxWarning: 'bool' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not subscriptable
3) Check you are not trying to access elements of a function
Check you are not trying to access an index on a method instead of the results of calling a method.
txt = 'Hello World!'
# Incorrectly getting the first word
>>> txt.split[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable
# The correct way
>>> txt.split()[0]
'Hello'
You will get a similar error for functions/methods you have defined yourself:
def foo():
return ['Hello', 'World']
# Incorrectly getting the first word
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable
# The correct way
>>> foo()[0]
'Hello'
Solutions List
A) Initialize the value
B) Don’t shadow built-in names
Solutions Detail
A) Initialize the value
Make sure that you are initializing the array before you try to access its index.
map = ['Hello']
print(map[0])
Hello
B) Don’t shadow built-in names
It is generally not a great idea to shadow a language’s built-in names as shown in the above solution as this can confuse others reading your code who expect map
to be the builtin map
and not your version.
If we hadn’t used an already taken name we would have also got a much more clear error from Python, such as:
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
But don’t just take our word for it: see here
Further Information
- Python 2: Subscriptions
- Python 3: Subscript notation
@Gerry