28

What does unsubscriptable mean in the context of a TypeError as in:

TypeError: 'int' object is unsubscriptable

EDIT: Short code example that results in this phenomena.

a=[[1,2],[5,3],5,[5,6],[2,2]]
for b in a:
    print b[0]

> 1
> 5
> TypeError: 'int' object is unsubscriptable
Theodor
  • 4,937
  • 12
  • 38
  • 53
  • 7
    Please include the code that produced the message. Please include the **smallest** sample of code that actually produces this error message. – S.Lott Nov 08 '10 at 12:15
  • 2
    Good start. Thanks. Step 2. Print the values of `b`. You can cut down the example to just one specific values of `b` that has this problem. Can you do that next step, too? – S.Lott Nov 08 '10 at 15:22
  • @S.Lott - Ok should be more clear now. – Theodor Nov 09 '10 at 09:16
  • 2
    Finally, What is the value of `b` when the error is printed? Include that in your question. – S.Lott Nov 09 '10 at 10:53
  • If you used a print debug before posting this question like ```print "debug: %r" % b; print b[0]``` then you would be able to find the the issue byself ;). It took me 2 minutes to understand your problem. – Andrei.Danciuc Jun 07 '18 at 10:38
  • 1
    In general, it simply is when `you are trying to get an element out of something that isn’t a dictionary, list, or tuple` – AzyCrw4282 Jul 12 '20 at 16:02

4 Answers4

45

It means you tried treating an integer as an array. For example:

a = 1337
b = [1,3,3,7]
print b[0] # prints 1
print a[0] # raises your exception
kichik
  • 28,340
  • 4
  • 77
  • 97
13

The problem in your sample code is that the array "a" contains two different types: it has 4 2-element lists and one integer. You are then trying to sub-script every element in "a", including the integer element.

In other words, your code is effectively doing:

print [1,2][0]
print [5,3][0]
print 5[0]
print [5,6][0]
print [2,2][0]

That middle line where it does "5[0]" is what is generating the error.

Sean Reifschneider
  • 1,221
  • 10
  • 16
9

You are trying to lookup an array subscript of an int:

>>> 1[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is unsubscriptable

That is, square brackets [] are the subscript operator. If you try to apply the subscript operator to an object that does not support it (such as not implementing __getitem__()).

camh
  • 36,335
  • 11
  • 57
  • 64
0

I solved this converting my variable from list to array!

import numpy as np
my_list = API.get_list()
my_array = np.array(my_list)

Even working and be a false positive, this solved my 'problem'

alvescleiton
  • 746
  • 8
  • 7