‘int’ object is not subscriptable – Python Error

Total
0
Shares

‘int’ object is not subscriptable is a Python type error which occurs when you try to access “index” on int variables.

a = 1
print(str(a[0]))

This code will throw, 'int' object is not subscriptable error because here we have assigned a = 1 which means a is an integer. In the next line, we are printing the 0th index of a, print(str(a[0])), which is incorrect.

The error screen will look like this –

python error int object is not subscriptable

In type unsafe languages like javascript, php, python etc., we can assign int to float or int to string or string to boolean but it doesn’t work for arrays.

Arrays needs to be defined explicitly because, internally, they are not a value else the location of values. It means an array variable holds the address in memory location from where your first element starts.

So, the right way of implementing the above code is –

a = ['Ironman', 'Captain America', 'Thor', 'Hulk']
print(str(a[0]))
// Output: Ironman

Python will throw the same error if you try to access a multidimensional index from single dimensional array. Or more precisely, large dimensional index than the maximum array dimension.

a = ['Ironman', 'Captain America', 'Thor', 'Hulk']
print(str(a[0][1]))
// Error: 'int' object is not subscriptable

    Tweet this to help others

Live Demo

Open Live Demo