Why exactly in this example is it giving me "NoneType object is not subscriptable"?

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/lessons/python-functions-lists-cc/exercises/append-sum

Hello,

in the end I looked for the solution to this exercise but am however still curious to know why exactly my code was given “NoneType object is not subscriptable”, that way I hopefully don’t repeat the same error. So this was my code:

def append_sum(lst):
  sum1 = lst[-1] + lst[-2]
  lst = lst.append(sum1)
  sum2 = lst[-1] + lst[-2]
  lst = lst.append(sum2)
  sum3 = lst[-1] + lst[-2]
  lst = lst.append(sum3)
  return list

Thank you.

What does your call to the function look like?

1 Like

This is what is written at the end of the exercise:

print(append_sum([1, 1, 2]))

I apologize if I’m not giving you the answer you’re looking for.

That line isn’t still in the code, is it?

1 Like

Hi @ai-2090,

The NoneType object, namely None, is what is assigned to lst in this statement:

  lst = lst.append(sum1)

Then your code attempts to subscript lst here:

  sum2 = lst[-1] + lst[-2]

See the following:

2 Likes

Thank you @mtf and @appylpye for your help, I think I’m getting it now, thanks also to a reply I got on my other topic concerning NoneType. Later in the day I’ll go as well through the link appylpye provided.

Have a nice day.

2 Likes

Nice strategy you used about typeerror nonetype object is not subscriptable

The error is self-explanatory. You are trying to index None. You can not, because ‘NoneType’ object is not subscriptable. This means that you tried to do:

None[something]

In general, the error means that you attempted to index an object that doesn’t have that functionality. You might have noticed that the method sort() that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.