We will learn, with this explanation, about the TypeError
object is not subscriptable and why we get this error. We will also learn how to fix this error in Python.
TypeError: 'type' object is not subscriptable Error in Python
Let’s jump into the code to show you an example of how it comes about and how to fix it. It is easy to fix, so let’s look at the code here.
Employee_Name='Denial' Empty_List= Employee_Name_len=len(Employee_Name) while Employee_Name_len > 0: Empty_List+=str[Employee_Name_len-1] Employee_Name_len=Employee_Name_len-1 print(Empty_List)
After running the above Python script, we will get an error:
TypeError: 'type' object is not subscriptable
So, what is the problem with the script? Well, the actual error is here
We can fix that in a second, but for demonstration purposes, we will demonstrate exactly what is going on in this code and why we get this error.
In this scenario, we have a variable called
Employee_Name, which has six letters stored. If we get the indexes of the
Employee_Name value, that would be 0 to 5.
In the next line, we want to create an empty list that works fine. In the third line, we will get the string length, which in that instance is 6; however, it is important to remember that the
Employee_Name variable has a length of 6, but only one value, which goes from zero to five.
Now, we have a
while statement that loops while the
Employee_Name_len length is greater than zero. In this loop, in the first line, we will increment
Empty_List in each iteration.
Generally, when we use string typecasting, we do something like
Instead of using open and close brackets, we are using square brackets; that is why it does not recognize it. It recognizes the
Before fixing the problem, we must understand what is happening in the last two lines. In the second last line, we are going one step back to bring the index value to five, and then we do the same thing in the next line for the next iteration.
We can fix this error easily. We know
str is a function, and we cannot use it like this.
It looks like we are trying to reference that back to the variable if we change
Employee_Name[Employee_Name_len-1]. As we know,
Employee_Name has index values 0 to 5.
Let’s run this Python script. Until it goes down to zero, it will keep iterating the
Employee_Name='Denial' Empty_List= Employee_Name_len=len(Employee_Name) while Employee_Name_len > 0: Empty_List+=Employee_Name[Employee_Name_len-1] Employee_Name_len=Employee_Name_len-1 print(Empty_List)
We can see no error occurring in the console. We get reverse list items of a string.
['l', 'a', 'i', 'n', 'e', 'D']