TypeError: 'int' object is not subscriptable

Sorry to bother you lads, I am new to programming so i am not sure why i got this error. Anyone keen to point out what went wrong? Thank you! :slight_smile:

In this problem set, i am trying to calculate the sum of the digits of 3^99

an_int = 3**99
a_string = str(an_int)
a_list = list(a_string)

total = 0 
list_no = len(a_list))

for i in range(list_no):
    total = total + int(list_no[i])

print(total)

Hi @script .

Have you checked the error code? Normally it points you to the location of the error (possibly a little downstream though). If you double check the code you posted you’ll find an unmatched paranthesis but I assume that was a typo, ignoring that for now I get a type error that flags up this line: total = total + int(list_no[i]). What specifically does that error code say is wrong? That’s a great way to start debugging.

Hey there @tgrtim

First of all, thank you for replying. Regarding the unmatched paratheses, yes that was a typo (my bad) And the error message i got was something similar to yours

error

Since it said that the object is not subscriptable, i was wondering if it has something to do with my variables in my first few lines of code. What do you think? :thinking:

Let’s break it down a little further. An int object is not subscriptable. Well int objects are realtively straightforward but what does subscriptable refer to- https://stackoverflow.com/questions/216972/what-does-it-mean-if-a-python-object-is-subscriptable-or-not

Roughly speaking an object which stores other items is subscriptable. So if the warning states an int object is not subscriptable (perfectly true) where in your code have you attempted to access items contained in another object? Because at one of those points you’ve actually passed an integer object.

1 Like

I looked through my code again and found an error, apparently it should be something like this

an_int = 3**99
a_string = str(an_int)
a_list = list(a_string)

total = 0 
list_no = len((a_list))

for i in range(list_no):
    total = total + int(a_list[i])

print(total)    

i switched ‘total = total + int(list_no[i])’ to ‘total = total + int(a_list[i])’ which allowed the loop to run properly. Thank you for your help @tgrtim !!! :grin:
Guess i’ll be able to sleep properly tonight .

2 Likes