Objects in Python can be subclassed in some cases. As such, they can contain and contain other objects, but an integer cannot. In Python, whole numbers are stored in objects called "Integers." An error will occur if we try to subscript an integer. This article will focus on a specific Python programming error—the TypeError: int object is not subscriptable—and how to fix it. And we'll talk about all the ways you can fix that mistake, too.
For what reason do we run into the "TypeError: int object is not subscriptable Error?"
A string, list, tuple, or even a dictionary can be iterated over. However, iterating over a single integer or a set of numbers is not possible.
Therefore, if you encounter this error, you are either trying to iterate over an integer or are incorrectly treating an integer as an array.
Please note that I used the ddmmyy format for the birth date (dob variable) in the following example. In spite of my best efforts, I was unable to determine the birth month. The "TypeError: int object is not subscriptable" error message was thrown.
Resolution of "TypeError: int object is not subscriptable
This error can be fixed by casting the integer to an iterable data type, such as a string.
And if you converted a value to an integer and then ran into trouble, you'll want to convert it back. Examples include a string, tuple, list, and so on.
The above error-causing code finally ran smoothly after I changed the dob variable to a string:
Fixing This Common Mistake
Keep the following in mind and you won't make that mistake:
Consistently give variables meaningful names
Variable names should always reflect the information they contain.
You shouldn't name a variable the same as a built-in Python function, module, or constant.
Cause is discussed in the second section of our message.
This alert indicates that a whole number (an integer) is being handled as though it were a subscriptable variable. Zero is not int object is not subscriptable object, and integers are not either. Subscripting is limited to objects. That can themselves hold other objects, such as strings, lists, tuples, and dictionaries.
To put it another way: what does it mean when an object is not subscriptable?
If an object can hold other objects, it is considered a subscriptable object in Python. Python objects that can be subscripted include strings, tuples, lists, and dictionaries, among others.
➟ If Integers can be subscripted, then why can't they?
To put it simply, integers are whole numbers. You can't put anything inside of them. Furthermore, the __getitem__() method is implemented by subscriptable objects but not integer objects.
The problem can be easily solved by treating the user's input number (num) as a string, so that individual digits can be accessed via index. Convert each string of digits to an integer and add them up.