Why my function is returning None in this example?

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

Hello,

I need to know and actually understand the None thing in Python, starting at least with this code example:

def append_size(lst):
lst = lst.append(len(lst))
return lst

Why exactly is it returning None? Slowly I’m becoming anxious with my coding because I’m never sure if I will get None or the value I want to see. That’s because I actually don’t quite understand yet how these things actually work in Python.

Thank you.

Hi @ai-2090,

The append method of list adds the specified item to the end of the list from which it is called, then returns None.

Instead of this:

  lst = lst.append(len(lst))

… you should do this …

  lst.append(len(lst))

The former does append the value of len(lst) to lst, but then it assigns None to lst.

2 Likes

I think I’m getting it now. If I understood well, and please correct me if not so that I won’t add it to my notes in that case, append function behaves more or less like sort function, i.e. it changes the list-in-place (if that’s the right term in English) but if assigned to a variable will return None?

Another thing that confused me was seeing a code line written that way - lst.append(len(lst)) - somehow I got used to firstly see things being assigned to a variable before being returned, I find it kinda odd to see a line written just like that, but now I see that it can go that way as well, I’ll try not to forget it.

2 Likes

Yes, the sort method and the append method of list both alter, in place, the list from which the method is called. In addition, they both have a return value of None. If you assign the calling expression of either of the methods to a variable, that variable will then have a value of None.

2 Likes