Code challenge - append size of list to list

Hi!

I’m working through some of the code challenges in the Python 3 course. I have a question about one featured here in particular:

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-lists

Brief summary of the challenge: create a function which accepts a list as a parameter, calculates the length of the list, and then appends the length of the list onto the list itself.

I almost came up with the solution but I used a less wordy structure which resulted in printing ‘none’ rather than the list with the list length appended. I’m curious to know why my code results with this output. The correct code is thus:

#Write your function here
def append_size(my_list):
  my_list.append(len(my_list))
  return my_list

#Uncomment the line below when your function is done
print(append_size([23, 42, 108]))

The code I wrote was:

#Write your function here
def append_size(my_list):
  return my_list.append(len(my_list))

#Uncomment the line below when your function is done
print(append_size([23, 42, 108]))

Is there a reason why one can’t build the function code into the return statement? Why is ‘none’ the result, rather than a syntax or other error?

Any help appreciated :slight_smile:

Different methods behave differently. We have to look at the documentation and/or do some experimentation to better understand that behavior.

The append method mutates/modifies a list by adding an item to the end of the list, but the method itself returns None. It doesn’t return the mutated list (even though the list is indeed mutated).

Contrast this with a method like pop. It mutates/modifies a list by removing an item from a list, and it returns the item that it removed.

x = [1, 2, 3]

y = x.append(4)
print(x) 
# [1, 2, 3, 4] (The list is mutated)
print(y) 
# None (The return value of the append method is None)

z = x.pop()
print(x) 
#  [1, 2, 3] (The list is mutated)
print(z) 
# 4  (The return value of the pop method is the item that was removed)
2 Likes

Cool, that’s well explained and makes sense, thank you. I suppose it follows that it rarely (if ever?) makes sense to use a function such as .append() in the definition a variable, as it would always return none. Useful to understand the mechanics behind the built in functions a little!

1 Like

Yes, there is no point in writing

y = x.append(4)

It was only for illustrative purposes. If we wanted to append an item, we would just write

x.append(4)

Great question OC. I wrote the same code as you and was wondering why it returned the mutated list AND None in the output