Typeerror int object is not subscriptable

Typeerror int object is not subscriptable : Step By Step Fix

Typeerror int object is not subscriptable error generates because int object does not contain inner object implicitly like List etc. Actually few of the python object are subscriptable because they are a collection of few elementary objects.

Typeerror int object is not subscriptable ( Cause with Example ) –

Let’s see the root cause of this error. Because this particular error may arise in so many cases but the root cause will be the same. The way to solve it will always be the same.

var = 500
print(type(var))
subscript=var[0]

"<yoastmark

 

Typeerror int object is not subscriptable (How to avoid) –

We need to check the object type before applying subscripting it. Here is an example of this.

var = 500
var_type=type(var)
print(var_type)
if(var_type!=int):
  subscript=var[0]
else:
  print("Sorry! Int object is not subscriptable")

"<yoastmark

Here we have seen that we have already checked the type of a variable before subscripting. Once we assure that this is not a subscriptable object we will bypass the code which generates this error. This is the way which helps to avoid this error.

Typeerror int object is not subscriptable (Solution)-

 

Well, Incase If you want to extract the last two digits of the Integer value. I know we all think to apply the subscripting. But directly doing it will raise the error int object is not subscriptable. So what’s the solution Right?

Hey! It too easy we fill firstly typecast the int variable into “str” object. Then we can do the subscripting easily.

var = 50011
var_type=type(var)
print(var_type)
if(var_type==str):
  subscript=var[-2:]
  print(subscript)
else:
  var=str(var)
  subscript=var[-2:]
  print(subscript)

Let’s run the above code and check the output.

"<yoastmark

So this the best way to Fix the error int object is not subscriptable by typecasting it into “str” object. Now we can slice it or subscript over it .

End Notes-

Well, This is one of the common errors for every python developer. I hope this exploration ( int object is not subscriptable ) works for you. In case you have some thoughts about it, please let us know via comment.

Thank You

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner