In Python some objects are subscriptable. It means that they contain, or can contain, other objects. Integers are used to store whole numbers so that are not a subscriptable object. If programmer treat an integer like a subscriptable object, an error will be raised like “TypeError : ‘int’ object is not subscriptable“.
If you noticed this is TypeError and it occurs when you try to perform operation that’s doesn’t support on object for example when you concatenate string and int then it will throw TypeError . You can more detail on [Solved] TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’.
Example : TypeError: ‘int’ object is not subscriptable
In this example, user is inserting date of birth in the format of DDMMYYYY then parse this date in Date (DD), Month(MM) and Year(YYYY).
dob = int(input("When is your date of birth? (ddmmyyyy) "))
day = dob[0:2]
month = dob[2:4]
year = dob[4:8]
print("Day:", day)
print("Month:", month)
print("Year:", year)
Output
When is your date of birth? (ddmmyyyy) 19051987
Traceback (most recent call last):
File “”, line 1, in
runfile(‘C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py’, wdir=’C:/Users/saurabh.gupta/Desktop/Python Example’)
File “C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 705, in runfile
execfile(filename, namespace)
File “C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 102, in execfile
exec(compile(f.read(), filename, ‘exec’), namespace)
File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 30, in
day = dob[0:2]
TypeError: ‘int’ object is not subscriptable
In this above example, user input date of birth (19051987) and convert this date to int. Which is now whole number and not subscriptable. now in code try to parse this date of birth in form of Day (DD), Month (MM) and Year (YYYY). Because it’s whole integer number when you try to parse this integer value will through exception as “TypeError: ‘int’ object is not subscriptable‘
Solution
In this above program issue is because programmer is explicitly type casting the string date of birth to integer which is whole number and not subscriptable to resolve this problem programmer need to remove this explicit integer type casting as below.
dob = input("When is your date of birth? (ddmmyyyy) ")
day = dob[0:2]
month = dob[2:4]
year = dob[4:8]
print("Day:", day)
print("Month:", month)
print("Year:", year)
Output
When is your date of birth? (ddmmyyyy) 19051987
Day: 19
Month: 05
Year: 1987
To learn more on exception handling follow the link Python: Exception Handling.
If this blog for solving KeyError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.